Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum by increment postgres

how to calculate the sum of points each week?

Table: essai

Here is the table and the last column (sum) is the resulsutat I want to get.

Table

like image 566
Bak Avatar asked Sep 06 '25 14:09

Bak


2 Answers

You can use the window variant of sum:

SELECT *,
       SUM(opints) OVER (ORDER BY number_week ASC
                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM   essai
like image 175
Mureinik Avatar answered Sep 08 '25 10:09

Mureinik


if:

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

then:

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)
like image 24
Vao Tsun Avatar answered Sep 08 '25 11:09

Vao Tsun