I need to run a query to sort out records for the first time an event occurs during the day, and the last time an event happens duri开发者_如何学编程ng the day, and run the report to include a week of recorded history on the system. This is in a SQL2005 database, but I haven't found anything to help me narrow things down to just a first occurrance and a last occurance.
-- 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
精彩评论