前端之家收集整理的这篇文章主要介绍了
计算PostgreSQL中的累计总和,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
403_0@
我想找到字段的累积或运行量,并将其从分段插入表中。我的分期结构是这样的:
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来实现这个结果。
任何人都可以建议如何实现这个结果集?
基本上,这里需要一个
window function。这是当今的标准
功能。除了正版窗口
函数之外,还可以通过附加OVER子句在Postgres中使用任何聚合
函数作为窗口
函数。
这里的特殊难题是获取分区和排序顺序:
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这里。
每行的总和从分区中的第一行计算到当前行,这是之后的累积或运行总和。 The manual:
The default framing option is RANGE UNBOUNDED PRECEDING
,which is the
same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
.
现在,ORDER BY月份将不会使用月份名称的字符串。 Postgres将根据区域设置按字母顺序排列。如果您的实际日期值存储在表格中,您可以正确排序。
如果没有,我建议用表中的date
型单列列替换ea_year和ea_month。
>转换你所拥有的to_date()
:
to_date(ea_year || ea_month,'YYYYMonth') AS mon
>为了显示,您可以获得to_char()
的原始字符串:
to_char(mon,'Month') AS ea_month
to_char(mon,'YYYY') AS ea_year
虽然卡住了不幸的布局,这将工作:
SELECT ea_month,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;