累积计数总和

时间:2014-03-01 01:08:31

标签: sql count sum

我想知道累计金额是否可以计算。我想与之合作的一个例子是今年影响美国的暴风雨。我想要一个结果集,其中列出了2014年的月份,以及直到那个月影响美国的累积风暴总数。我希望得到一些3列 - Month,NumberofStorms和CumulativeSum看起来像这样:

Month        NumberofStorms     CumulativeSum
-----------------------------------------------
Jan              2                   2
Feb              1                   3
Mar              1                   4
Apr              0                   4
May              0                   4
Jun              0                   4
Jul              0                   4
Aug              0                   4    
Sep              1                   5
Oct              3                   8
Nov              5                  13 
Dec              8                  21

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以向SUM()添加窗口:

SELECT "Month"
      ,"NumberofStorms"
      ,SUM("NumberofStorms") OVER(ORDER BY "Month" ROWS BETWEEN unbounded preceding and current row) AS CumulativeSum
FROM Table1

演示:SQL Fiddle

注意:月份在演示中按字母顺序排序,没有输入实际日期,因为它只是一个示例场景。

更新:让我们假设基表只是MonthStormName,你需要一个cte /子查询来获得一个你可以在上面的运行总数中使用的计数:

SELECT "Month"
      ,"NumberofStorms"
      ,SUM("NumberofStorms") OVER(ORDER BY "Month" ROWS BETWEEN unbounded preceding and current row) AS CumulativeSum
FROM (SELECT "Month",COUNT("Name") AS "NumberofStorms"
      FROM Weather
      GROUP BY "Month"
      ) AS Sub

答案 1 :(得分:0)

您可以在没有子查询的情况下执行累积求和。如果NumberOfStorms是原始数据的一部分:

SELECT "Month", "NumberofStorms",
       SUM(NumberofStorms) OVER (ORDER BY "Month" ROWS BETWEEN unbounded preceding and current row) AS CumulativeSum
FROM Weather
GROUP BY "Month", NumberOfStorms;

并且,在许多数据库中,row子句是不必要的,因此以下内容也应该有效:

SELECT "Month", "NumberofStorms",
       SUM(NumberofStorms) OVER (ORDER BY "Month") as CumulativeSum
FROM Weather
GROUP BY "Month", NumberOfStorms;

如果NumberOfStorms真的来自count(*),那么你会这样做:

SELECT "Month", count(*) as "NumberofStorms",
       SUM(count(*)) OVER (ORDER BY "Month") as CumulativeSum
FROM Weather
GROUP BY "Month";

首先,看累积和和窗口/分析函数的组合看起来有点奇怪,你会很​​快习惯它。