Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulate a summarized column

Tags:

sql

I could need some help with a SQL statement. So I have the table "cont" which looks like that:

cont_id     name       weight
----------- ---------- -----------
1           1          10
2           1          20
3           2          40
4           2          15
5           2          20
6           3          15
7           3          40
8           4          60
9           5          10
10          6          5

I then summed up the weight column and grouped it by the name:

name       wsum
---------- -----------
2          75
4          60
3          55
1          30
5          10
6          5

And the result should have a accumulated column and should look like that:

name       wsum        acc_wsum
---------- ----------- ------------
2          75          75
4          60          135
3          55          190
1          30          220
5          10          230
6          5           235

But I didn't manage to get the last statement working..

edit: this Statement did it (thanks Gordon)

select t.*,
    (select sum(wsum) from (select name, SUM(weight) wsum
    from cont
    group by name)
    t2 where t2.wsum > t.wsum or (t2.wsum = t.wsum and t2.name <= t.name)) as acc_wsum
from (select name, SUM(weight) wsum
from cont
group by name) t
order by wsum desc
like image 535
Ulrich Fischer Avatar asked Dec 13 '12 14:12

Ulrich Fischer


2 Answers

So, the best way to do this is using cumulative sum:

select t.*,
       sum(wsum) over (order by wsum desc) as acc_wsum
from (<your summarized query>) t

The order by clause makes this cumulative.

If you don't have that capability (in SQL Server 2012 and Oracle), a correlated subquery is an easy way to do it, assuming the summed weights are distinct values:

select t.*,
       (select sum(wsum) from (<your summarized query>) t2 where t2.wsum >= t.wsum) as acc_wsum
from (<your summarized query>) t

This should work in all dialects of SQL. To work with situations where the accumulated weights might have duplicates:

select t.*,
       (select sum(wsum) from (<your summarized query>) t2 where t2.wsum > t.wsum or (t2.wsum = t.wsum and t2.name <= t.name) as acc_wsum
from (<your summarized query>) t
like image 181
Gordon Linoff Avatar answered Oct 04 '22 15:10

Gordon Linoff


try this

;WITH CTE
AS
(
 SELECT *,
ROW_NUMBER() OVER(ORDER BY wsum) rownum
FROM @table1
 ) 
 SELECT 
 c1.name, 
 c1.wsum,
 acc_wsum= (SELECT SUM(c2.wsum) 
                   FROM cte c2
                   WHERE c2.rownum <= c1.rownum)
 FROM CTE c1;

or you can join instead of using subquery

;WITH CTE
AS
(
 SELECT *,
ROW_NUMBER() OVER(ORDER BY usercount) rownum
 FROM @table1
) 
 SELECT 
 c1.name, 
 c1.wsum,
 acc_wsum= SUM(c2.wsum) 
 FROM CTE c1
 INNER JOIN CTE c2 ON c2.rownum <= c1.rownum
 GROUP BY c1.name, c1.wsum;
like image 39
SRIRAM Avatar answered Oct 04 '22 17:10

SRIRAM