我需要运行一个查询,以便在白天第一次发生事件时对记录进行排序,以及在白天最后一次事件发生,并运行报告以在系统中包含一周记录的历史记录。这是在一个SQL2005数据库中,但是我没有找到任何东西可以帮助我将事情缩小到第一次出现和最后一次出现。
答案 0 :(得分:1)
-- Test data in table @T
declare @T table(id int, dt datetime)
insert into @T values (1, '2011-01-01T10:00:00')
insert into @T values (2, '2011-01-01T11:00:00')
insert into @T values (3, '2011-01-01T12:00:00')
insert into @T values (4, '2011-01-02T20:00:00')
insert into @T values (5, '2011-01-02T21:00:00')
insert into @T values (6, '2011-01-02T22:00:00')
-- First day of interval to query
declare @FromDate datetime = '2011-01-01'
-- Add 7 days to get @ToDate
declare @ToDate datetime = dateadd(d, 7, @FromDate)
;with cte as
(
select *,
row_number() over(partition by datediff(d, T.dt, 0) order by T.dt) as rnMin,
row_number() over(partition by datediff(d, T.dt, 0) order by T.dt desc) as rnMax
from @T as T
where T.dt >= @FromDate and T.dt < @ToDate
)
select C.id, C.dt
from cte as C
where C.rnMax = 1 or C.rnMin = 1
order by C.dt