我希望t.Notes
与s.SR_Service_RecID
t.Date_Start
和t.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
)
答案 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
)