计算我表格范围内的出现次数

时间:2013-07-10 17:30:36

标签: sql count sql-server-2012

当我尝试将特定时间范围内的出现次数相加时,我有以下问题。

假设我有下表:

     Date                New
     2013-01-01           1
     2013-01-01           0
     2013-01-01           0                                  
     2013-01-01           1
     2013-01-02           1
     2013-01-02           0
     2013-01-03           1
     2013-01-03           1
     2013-01-04           0
     2013-01-04           1
     2013-01-05           1

我想要计算每两天发生的“新”数量。

在上面提供的示例中,我期望得到的结果如下:

     Date                 Result
     2013-01-01/02           3
     2013-01-02/03           3
     2013-01-03/04           3
     2013-01-04/05           2

你可以看到我在计算每两天发生的次数。

请注意我正在使用一张大桌子(> 10米线),我需要>要生产50个不同的范围(考虑每组2天作为范围)。

我正在使用SQL Server 2012。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

这是一种聚合数据一次然后使用窗口函数进行计算的方法。当前一个日期比当前日期小1时,计算只会添加前一个值:

select date,
       (cnt + (case when DATEDIFF(day, prevdate, date) = 1 then prevcnt else 0 end)) as Result
from (select date, SUM(new) as cnt,
             lag(DATE) over (order by date) as prevdate,
             lag(SUM(new)) over (order by date) as prevcnt
      from t
      group by date
     ) t

答案 1 :(得分:1)

Gordon Linoff对SQL 2012的回答更好,但我认为我会尝试在以前版本中使用的替代方案,因为这是一个有趣的问题。

SELECT #table1.[Date], (SUM(new) + t.cnt2) AS cnt
FROM #table1
INNER JOIN (SELECT [Date], SUM(new) AS cnt2 
           from #table1 
           GROUP BY #table1.[date]) t ON #table1.[date] = t.[date]-1
GROUP BY #table1.[date], t.cnt2