【问题标题】:SQL - Summing events by date (5 days at a time)SQL - 按日期汇总事件(一次 5 天)
【发布时间】:2011-11-29 04:55:32
【问题描述】:

我要做的是计算给定数据范围内滑动 5 天期间呼叫中心事件的数量;如果事件计数超过(例如)10,我需要提醒经理。我已经创建了包含日期及其相应呼叫中心事件计数的数据集。

  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)

不知何故,我需要弄清楚如何以 5 个连续天为一组进行查询,并对事件数求和。像

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

但这不正常。我的替代方案是可怕的 foreach 日期循环,将日期和日期 + 5 之间的事件相加。我不想这样做。

我们将不胜感激。

谢谢。

【问题讨论】:

    标签: sql sql-server-2008 datepart


    【解决方案1】:

    你可以试试这样的:

    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'
    

    样本输出:

    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
    

    【讨论】:

      【解决方案2】:

      您可以使用一年中的某一天。比如:

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

      很明显,当这一年过去的时候,它会倒塌,但这是一个开始。

      【讨论】:

      • 这将创建 5 天的不相交集,而不是像 OP 描述的那样重叠。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多