2

What I'm trying to do is calculate the number of call center events for a sliding 5 day period for a given range of data; if the event count exceeds (for example) 10, I need to alert the managers. I've already created the data set which contains dates and their cooresponding call center event counts.

  Date      Events   w01 w02 w03 w04 w05
11/01/2011    5       * 
11/02/2011    2       *   *     
11/03/2011    4       *   *   *
11/04/2011    1       *   *   *   *
11/05/2011    0       *   *   *   *   *
11/06/2011    2           *   *   *   *
11/07/2011    7               *   *   *
11/08/2011    0                   *   *
11/09/2011    5                       *


I would like to have the results in this format
w01: 12 events
w02:  7 events
w03: 14 events (alert sent)
w04: 10 events
w05: 14 events (alert sent)

I somehow need to figure out how to query this in groups of 5 contiguous days and sum the number of events. Something like

select sum(events)
from tablename
group by datepart(dd, date) * 5

but that is not working right. My alternative is the dreaded foreach date loop, summing the event between date and date + 5. I would prefer not to do that.

A nudge in the right direction would be appreciated.

Thanks.

Andy Evans
  • 6,997
  • 18
  • 72
  • 118

2 Answers2

3

You can try something like this:

select
    Date,
    (select sum(events)
     from tablename d2
     where abs(datediff(DAY, d1.Date, d2.Date)) <= 2) as EventCount
from
    tablename d1
where
    Date between '11/03/2011' and '11/07/2011'

Sample output:

Date        EventCount
11/03/2011  12
11/04/2011  9  ** Note that the correct value for w02 is 9, not 7
11/05/2011  14
11/06/2011  10
11/07/2011  14
mellamokb
  • 56,094
  • 12
  • 110
  • 136
1

You could use the day of the year. Something like:

select datepart(dy, eventdate)/5 AS IntervalNo, sum(events)
from tablename
group by datepart(dy,eventdate)/5

Obviously that would fall over when the year rolls over, but it's a start.

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
SteveCav
  • 6,649
  • 1
  • 50
  • 52