HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to SUM previous sum, e.g N = (N-1) + (N-2) + ... + 1?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
sumprevioushow

Problem

I have a table name "TABLE_A (id integer, no integer)" .

I want to sum "no" with group by "id" and current "sum of no" = previous "sum of no"

Here is my code :

1/ Create table & insert data:

create table table_a (id int, no int);

insert into table_a values(1, 10);
insert into table_a values(1, 20);
insert into table_a values(1, 30);
insert into table_a values(2, 100);
insert into table_a values(2, 200);
insert into table_a values(2, 300);
insert into table_a values(3, 1);
insert into table_a values(3, 2);
insert into table_a values(3, 3);
insert into table_a values(3, 3);


2/ Desired result:

id | sum_of_no
--------------
1  | 60
2  | 660
3  | 669


3/ My solutions (ok):

with t_report_code_temp as
(   
select id, sum(no) as t_code
from table_a
group by id 
)
select a.id, sum(b.t_code)
from t_report_code_temp a 
join t_report_code_temp b on b.id <= a.id
group by a.id
order by 1


My question:

Could you give me the better way to solve ?

Solution

From Craig Ringer, ypercube.

Here my testing:

create table table_a (id int, no int);

insert into table_a  (1)
select a, a
from generate_series(1, 1000000) a


Craig Ringer's query

with t_report_code_temp(id, t_code) as
(   
select id, sum(no)
from table_a
group by id 
)
SELECT
  id,
  sum(t_code) OVER (ORDER BY id ASC)
FROM t_report_code_temp;

1.000.000 rows -> 5.5s
2.000.000 rows -> 7s   (run (1) twice)


ypercube's query

SELECT
  id,
  SUM(SUM(no)) OVER (ORDER BY id ASC) AS sum_of_no
FROM table_a
GROUP BY id ;

1.000.000 rows -> 3.7s
2.000.000 rows -> 5.5s   (run (1) twice)


I see the magic of window function. Thanks !

Code Snippets

create table table_a (id int, no int);

insert into table_a  (1)
select a, a
from generate_series(1, 1000000) a
with t_report_code_temp(id, t_code) as
(   
select id, sum(no)
from table_a
group by id 
)
SELECT
  id,
  sum(t_code) OVER (ORDER BY id ASC)
FROM t_report_code_temp;

1.000.000 rows -> 5.5s
2.000.000 rows -> 7s   (run (1) twice)
SELECT
  id,
  SUM(SUM(no)) OVER (ORDER BY id ASC) AS sum_of_no
FROM table_a
GROUP BY id ;

1.000.000 rows -> 3.7s
2.000.000 rows -> 5.5s   (run (1) twice)

Context

StackExchange Database Administrators Q#61407, answer score: 5

Revisions (0)

No revisions yet.