计算每个月的累积变化 - Postgres SQL问题

时间:2013-08-01 13:40:54

标签: sql postgresql

当我执行以下SQL查询时:

select yr,
       mn, 
       "%ind", 
       sum("%ind") OVER (order BY yr,mn) as "Sum%" 
from table2 
order by yr, mn; 

结果是:

  yr  | mn |        %ind        |       Sum%       
------+----+--------------------+------------------
 1996 |  2 |   18.1818181818182 | 18.1818181818182
 1996 |  2 |   9.09090909090909 | 81.8181818181818
 1996 |  2 |   9.09090909090909 | 90.9090909090909
 1996 |  2 |   9.09090909090909 |              100
 1996 |  3 |   12.1951219512195 |  112.19512195122
 1996 |  3 |   31.0975609756098 | 143.292682926829
 1996 |  3 |  0.609756097560976 | 199.390243902439
 1996 |  3 |  0.609756097560976 |              200
 1996 |  4 |    4.8780487804878 | 204.878048780488
 1996 |  4 |    24.390243902439 |  268.29268292683
 1996 |  4 |   14.6341463414634 | 298.780487804878
 1996 |  4 |   1.21951219512195 |              300

这是一个问题,因为我要做的是在给定月份添加列%ind通讯员的每一行,例如1996-3。此外,一旦月份发生变化,我希望它重新开始从0增加到100%。因此理想的表格是:

  yr  | mn |        %ind        |       Sum%       
------+----+--------------------+------------------
 1996 |  2 |   18.1818181818182 | 18.1818181818182
 1996 |  2 |   9.09090909090909 | 81.8181818181818
 1996 |  2 |   9.09090909090909 | 90.9090909090909
 1996 |  2 |   9.09090909090909 |              100
 1996 |  3 |   12.1951219512195 |   12.19512195122
 1996 |  3 |   14.0243902439024 |   86.585365853659
 1996 |  3 |  0.609756097560976 |   99.390243902439
 1996 |  3 |  0.609756097560976 |              100
 1996 |  4 |    4.8780487804878 |    4.878048780488
 1996 |  4 |   15.8536585365854 |   84.146341463415
 1996 |  4 |   14.6341463414634 |   98.780487804878
 1996 |  4 |   1.21951219512195 |              100

我的SQL查询缺少什么?

1 个答案:

答案 0 :(得分:1)

您需要将partition by BY yr,mn添加到窗口定义中。由于您没有定义分区(" group"),因此窗口函数对整个结果集进行操作:

此外,您必须找到另一列来定义一个月的值的稳定排序。假设你有例如一个由序列生成的ID列,这样的东西应该起作用:

select yr,
       mn, 
       "%ind", 
       sum("%ind") OVER (partition by yr,mn order by id) as "Sum%" 
from table2 
order by yr, mn; 

这是一个SQLFiddle示例:http://sqlfiddle.com/#!12/33838/1