Postgres增量求和

时间:2018-06-26 19:46:14

标签: sql postgresql select sum increment

每周如何计算总分?

表:essai

这是表格,最后一列(总和)是我想要获得的结果。

Table

2 个答案:

答案 0 :(得分:1)

您可以使用sum的窗口变体:

SELECT *,
       SUM(opints) OVER (ORDER BY number_week ASC
                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM   essai

答案 1 :(得分:0)

如果:

db=# create table m (w int, n text, p int);
CREATE TABLE
db=# insert into m values (4,'a',2),(3,'a',6),(2,'a',1),(1,'a',3);
INSERT 0 4

然后:

db=# with c as (select *,sum(p) over (partition by n order by w) from m)
select * from c order by w desc;
 w | n | p | sum
---+---+---+-----
 4 | a | 2 |  12
 3 | a | 6 |  10
 2 | a | 1 |   4
 1 | a | 3 |   3
(4 rows)