One way is to create a table (or some sort of derived table as below) to define the shifts. Then JOIN to that table:--Your Sample datadeclare @t table (UserID varchar(10), IncidentNo varchar(10), DateTime [datetime])insert @t select 'User1', 'XPI1243', '12/8/2008 9:00:01 PM' union allselect 'User2', 'XPI1243', '12/8/2008 9:45:01 PM' union allselect 'User2', 'XPI1243', '12/8/2008 10:20:35 PM' union allselect 'User1', 'XPI1243', '12/8/2008 11:55:00 PM' union allselect 'User1', 'XPI1243', '12/9/2008 1:12:10 AM' union allselect 'User2', 'XPI1243', '12/9/2008 5:05:41 AM' union allselect 'User1', 'XPI1243', '12/9/2008 5:55:01 AM' union allselect 'User1', 'XPI1243', '12/9/2008 9:00:01 PM' union allselect 'User2', 'XPI1243', '12/9/2008 9:45:01 PM' union allselect 'User2', 'XPI1243', '12/9/2008 10:20:35 PM' union allselect 'User1', 'XPI1243', '12/9/2008 11:55:00 PM' union allselect 'User1', 'XPI1243', '12/10/2008 1:12:10 AM' union allselect 'User2', 'XPI1243', '12/10/2008 5:05:41 AM' union allselect 'User1', 'XPI1243', '12/10/2008 5:55:01 AM'select * from @t where userid = 'user1' order by [datetime];with ShiftGroup (grp, startShift, endShift)as ( --Create a table with your Shifts for each dayselect v.number grp ,dateadd(hour, 21, dateadd(day, number, mn)) startShift ,dateadd(hour, 6, dateadd(day, number+1, mn)) endShiftfrom ( select datediff(day, mn, mx) days ,mn ,mx from ( select dateadd(day, datediff(day, 0, min([datetime])), 0) mn ,dateadd(day, datediff(day, 0, max([datetime])), 0) mx from @t ) d ) dinner join master..spt_values v on v.type = 'P' and v.number <= days)--Final Select GROUPed by Shiftselect t.UserID ,sg.startShift ,sg.endShift ,count(*) [requestCount]from ShiftGroup sginner join @t t on t.[datetime] >= sg.startShift and t.[datetime] <= sg.endshiftgroup by t.UserID ,sg.startShift ,sg.endShiftOUTPUT:UserID startShift endShift requestCount---------- ----------------------- ----------------------- ------------User1 2008-12-08 21:00:00.000 2008-12-09 06:00:00.000 4User1 2008-12-09 21:00:00.000 2008-12-10 06:00:00.000 4User2 2008-12-08 21:00:00.000 2008-12-09 06:00:00.000 3User2 2008-12-09 21:00:00.000 2008-12-10 06:00:00.000 3
Be One with the OptimizerTG