sql loop through results / group by / sort

2019-07-31 14:25发布

问题:

this is a follow on question from my previous post

I have the following code which will query a database of when our agents were logged on at a particular time. It works nicely for a given day, but I need to now do it for a selected time period. I am not sure where to start to adjust this! I'd need the results grouped by date and hour... so it would look as follows

date        hour    count
10/10/11    22      52
10/10/11    23      24
11/10/11    00      12
11/10/11    01      33

So the 24 hour period would be displayed for each date within the selected range.

ALTER procedure [dbo].[LoggedOnCountByHour]
    @DayToCheck datetime,
    @HelplineID int
as

select  dateadd(hour, N.number, @DayToCheck) as [date_hour], 
        DATEPART(hh,dateadd(hour, N.number, @DayToCheck)) as [Hour],
        count(L.ExpertRecID) as [count of users]
from master..spt_values as N
  left outer join WorkDetail as L
    on L.KickedOffTime > dateadd(hour, N.number, @DayToCheck) and
       L.LoginTime < dateadd(hour, N.number + 1, @DayToCheck)
left join PoolMembership P on P.ExpertRecID = L.ExpertRecID

where N.Type = 'P' and
      N.Number between 0 and 23 and
      P.HelplinePoolID = @HelplineID 
group by dateadd(hour, N.number, @DayToCheck), DATEPART(hh,dateadd(hour, N.number, @DayToCheck) )

any ideas!? Many thanks

回答1:

Something like this (not thoroughly tested)

alter procedure [dbo].[LoggedOnCountByHour]
        @FromDayToCheck datetime,
        @ToDayToCheck datetime,
        @HelplineID int
as

select  dateadd(hour, N.number, @FromDayToCheck) as [date_hour], 
        DATEPART(hh,dateadd(hour, N.number, @FromDayToCheck)) as [Hour],
        count(L.ExpertRecID) as [count of users]
from master..spt_values as N
  left outer join WorkDetail as L
    on L.KickedOffTime > dateadd(hour, N.number, @FromDayToCheck) and
       L.LoginTime < dateadd(hour, N.number + 1, @FromDayToCheck)
  left join PoolMembership P on P.ExpertRecID = L.ExpertRecID

where N.Type = 'P' and
      dateadd(hour, N.number + 1, @FromDayToCheck) <= @ToDayToCheck + 1 and
      P.HelplinePoolID = @HelplineID 
group by dateadd(hour, N.number, @FromDayToCheck), DATEPART(hh,dateadd(hour, N.number, @FromDayToCheck) )
order by [date_hour], [Hour]

Note: If you think that your time interval you are checking against is more than 2048 hours you should use a numbers table instead of master..spt_values.