计算PostgreSQL中的累计和

我想查找字段的累积或运行量,并将其从登台插入到表中。 我的分期结构是这样的:

ea_month id amount ea_year circle_id April 92570 1000 2014 1 April 92571 3000 2014 2 April 92572 2000 2014 3 March 92573 3000 2014 1 March 92574 2500 2014 2 March 92575 3750 2014 3 February 92576 2000 2014 1 February 92577 2500 2014 2 February 92578 1450 2014 3 

我希望我的目标表看起来像这样:

 ea_month id amount ea_year circle_id cum_amt February 92576 1000 2014 1 1000 March 92573 3000 2014 1 4000 April 92570 2000 2014 1 6000 February 92577 3000 2014 2 3000 March 92574 2500 2014 2 5500 April 92571 3750 2014 2 9250 February 92578 2000 2014 3 2000 March 92575 2500 2014 3 4500 April 92572 1450 2014 3 5950 

我真的很困惑如何去实现这个结果。 我想用PostgreSQL来实现这个结果。

任何人都可以build议如何去实现这个结果集?

基本上,你需要一个窗口function 。 这是当今的一个标准function。 除了真正的窗口函数之外,还可以使用任何聚合函数作为Postgres中的窗口函数,方法是附加一个OVER子句。

这里的特殊难点是分区和sorting的权利:

 SELECT ea_month, id, amount, ea_year, circle_id , sum(amount) OVER (PARTITION BY circle_id ORDER BY month) AS cum_amt FROM tbl ORDER BY circle_id, month; 

这里没有 GROUP BY

每行的总和从分区中的第一行计算到当前行,这是您之后的累计或运行总和。 手册 :

默认的框架选项是RANGE UNBOUNDED PRECEDING ,它与RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

现在, ORDER BY month 不能用于string的月份名称。 Postgres会根据区域设置按字母顺序sorting。 如果您的表中存储了实际的date值,则可以正确sorting。

如果不是的话,我build议用你表格中的单个datetypes列mon来代替ea_yearea_month

  • 使用to_date()变换你的东西:

     to_date(ea_year || ea_month , 'YYYYMonth') AS mon 
  • 为了显示,你可以用to_char()得到原始string:

     to_char(mon, 'Month') AS ea_month to_char(mon, 'YYYY') AS ea_year 

虽然卡住了不幸的布局,这将工作:

 SELECT ea_month, id, amount, ea_year, circle_id , sum(amount) OVER (PARTITION BY circle_id ORDER BY mon) AS cum_amt FROM (SELECT *, to_date(ea_year || ea_month, 'YYYYMonth') AS mon FROM tbl) ORDER BY circle_id, mon; 
Interesting Posts