2011-05-20 36 views
1

我有一個查詢,它返回一個日期時間字段和其他幾個字段。我想從另一個也有日期時間字段的表中添加一個字段。由於datetime字段不相關,所以我不能內聯這兩個表,所以我們不想將第一個表中的第一行加入到第一個表中的datetime字段後面。下面是我試圖去一個非功能性的僞查詢:嘗試使用日期時間字段連接表

SELECT DISTINCT 
     TripID AS 'ID', 
     @CURRDATE = CurrDate, 
     @GROUPID = GroupID, 
     UserEmail AS 'User', 
     RouteID AS 'Route', 
     (SELECT TOP (1) PatternNum 
      FROM tblMOEHistory 
     WHERE (GroupID = @GROUPID) 
      AND (TimeStamp > @CURRDATE) 
     ORDER BY TimeStamp) AS 'Pattern' 
    FROM tblMobileTrips 
ORDER BY 'Time'; 

我不知道是否有一種方法可以做到這一點,但我希望有人也許能夠幫助我。

回答

1

確實是可以使用加入...給這個鏡頭:

SELECT DISTINCT a.TripID AS 'ID', 
    a.CurrDate, 
    a.GroupID, 
    a.UserEmail AS 'User', 
    a.RouteID AS Route', 
    b.PatternNum 
from someTable a 
join tblMOEHistory b on a.GroupID = b.GroupID 
    and b.TimeStamp = (select MIN(TimeStamp) 
         from tblMOEHistory 
         where GroupID = a.GroupID 
         and TimeStamp > a.CurrDate) 
2

使用CROSS應用,可以在「參數化」的號召,tblMOEHistory(我假設你@GROUPID和每行@CURRDATE試圖)

喜歡的東西:

SELECT DISTINCT 
    M.TripID AS 'ID', 
    M.CurrDate, 
    M.GroupID, 
    M.UserEmail AS 'User', 
    M.RouteID AS 'Route', 
    MH.PatternNum AS 'Pattern' 
FROM 
    tblMobileTrips M 
    CROSS APPLY 
    (SELECT TOP (1) PatternNum 
    FROM tblMOEHistory MH 
    WHERE MH.GroupID = M.GroupID AND MH.TimeStamp > M.CurrDate 
    ORDER BY TimeStamp 
) MH 
ORDER BY 'Time'; 
相關問題