获取最长日期和最长时间

时间:2013-05-03 00:45:44

标签: sql sql-server-2008 tsql

我希望t.Notess.SR_Service_RecID t.Date_Startt.Time_Start相关联,因为单个时间条目可以有多个针对单张票的日期,我需要包括时间以获得最新的单一结果。

DECLARE @SD DATETIME,
        @ED DATETIME    

SET     @SD = DATEADD(dd, -14, GETDATE())
SET     @ED = GETDATE()

SELECT s.SR_Service_RecID
     , t.Notes

  FROM SR_Service s
       LEFT JOIN Time_Entry t 
              ON t.SR_Service_RecID = s.SR_Service_RecID

 WHERE s.Date_Closed BETWEEN @SD AND @ED

我在WHERE子句中尝试了2个子查询,一个用于t.Date_Start,一个用于t.Time_Start只能选择MAX个结果,但它会限制一些原因并且会有丢失的条目...可能不是正确的方法?

    AND t.Date_Start IN
        (
            SELECT  MAX(t.Date_Start)
              FROM  Time_Entry t
             WHERE  t.SR_Service_RecID = s.SR_Service_RecID
        )
    AND t.Time_Start IN
        (
            SELECT  MAX(t.Time_Start)
              FROM  Time_Entry t
             WHERE  t.SR_Service_RecID = s.SR_Service_RecID
        )

2 个答案:

答案 0 :(得分:1)

我认为这应该很接近。谜团是如何将您对不同日期和时间的任何数据类型组合成单个DateTime值。这是OP的练习。

select *
  from (
    select s.SR_Service_RecID, t.Notes, t.Date_Start, t.Time_Start,
      Row_Number() over ( partition by s.SR_Service_RecID order by <combined date/time> desc) as [RN]
      from SR_Service as s left outer join
        Time_Entry as t on t.SR_Service_RecID = s.SR_Service_RecID
      where @SD <= s.Date_Closed and s.Date_Closed <= @ED
    ) as Bob
  where RN = 1

答案 1 :(得分:0)

使用带有关键字EXISTS的子查询。外部查询的WHERE子句测试子查询返回的行是否存在。

SELECT s.SR_Service_RecID, t.Notes
FROM SR_Service s LEFT JOIN Time_Entry t ON t.SR_Service_RecID = s.SR_Service_RecID
WHERE s.Date_Closed BETWEEN @SD AND @ED
 AND EXISTS (
             SELECT 1
             FROM Time_Entry t2
             WHERE s.SR_Service_RecID = t2.SR_Service_RecID
             HAVING MAX(CAST(t2.Date_Start AS datetime) + t2.Time_Start) 
               = CAST(t.Date_Start AS datetime) + t.Time_Start
             )