尝试使用datetime字段连接表

时间:2011-05-20 18:01:26

标签: sql sql-server tsql

我有一个返回datetime字段和其他几个字段的查询。我想从另一个也有日期时间字段的表中添加一个字段。我不能内连接这两个表,因为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';

我不确定是否有办法做到这一点,但我希望有人可以帮助我。

2 个答案:

答案 0 :(得分:2)

使用CROSS APPLY,你可以“调整”对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';

答案 1 :(得分: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)