1

我想获得与最新的t.Notes相关联的- 由于在一个日期上可能有多个时间条目针对一张票,我需要包括时间以获得最新的单个结果。s.SR_Service_RecIDt.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 个子查询,一个用于 the 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
        )
4

2 回答 2

1

I think this should be close. The mystery is how to combine whatever data types you have for your separate dates and times into a single DateTime value. That's left as an exercise for the 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
于 2013-05-03T01:15:19.007 回答
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
             )
于 2013-05-03T08:30:26.007 回答