按增量 postgres 求和

sum by increment postgres

如何计算每周积分总和?

Table: 文章

这是table,最后一列(总和)是我想要得到的结果。

您可以使用 sum 的 window 变体:

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

如果:

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)