我有一个审计表,它将主表的“状态”值存储在多行中,每行都有一个日期/时间戳。让我们调用主表“Project”,它会在不同的状态变化中移动:Open,Pending,Closed。但有时项目可能会在关闭后重新打开。数据将是这样的:
ProjectId Date Status
1234 07-01-2015 Open
1234 07-03-2015 Pending
1234 07-05-2015 Closed
1234 07-06-2015 Open
我需要获取日期参数值,并确定项目“1234”在该给定日期的状态。
ex: Date=07-02-2015 would give me "Open"
Date=07-07-2015 would also give me "Open"
Date=07-03-2015 would give me "Pending"
我遇到的问题是SQL需要查看周围的行(如果有的话)
答案 0 :(得分:2)
1)将行限制为仅在窗口内具有日期的行。 2)按日期降序对结果进行排序(将最新的结果放在顶部) 3)选择第一行
DECLARE @CheckDate DATETIME = '07-07-2015',
@ProjectId INT = 1234
-- To ignore time, set the check date to the first millisecond of the
-- next day and use a less than operator
SET @CheckDate = DATEADD(dd, DATEDIFF(dd, 0, @CheckDate) + 1, 0)
SELECT TOP 1
[Status]
FROM [Project]
WHERE [ProjectId] = @ProjectId
AND [Date] < @CheckDate
ORDER BY [Date] DESC
答案 1 :(得分:0)
如果您有2012年或更高版本,可以使用Lead
执行此操作,如下所示:
declare @date datetime = '7-2-15' --or whatever
select ProjectID, Status from (
select *
, lead(date) over (partition by projectID order by date) as NextEvent
from MyTable) a
where @date between [date] and isnull(NextEvent, @date + 1)
否则,您可以使用lead
和自我加入来估算row_number
。
注意,根据日期的准确程度,您可能希望使用where @date >= date and @date < isnull(NextEvent, @date + 1)
而不是between
。