chrise
chrise

Reputation: 4253

sql sum all values in col x for values smaller than value of x in this row

How can I sum all values of c2 where the value in c1 is smaller or equal to the value of c1. I am confused as how to address the value of this row as the statement

sum(case c1 <= c1 then c2 else 0 end) 

does not make much sense. how can I make it something like

sum(case c1 <= c1_value_of_this_row then c2 else 0 end)

c1    c2
 1    10
 2     5
 1     3
 3     8

to

c1    c2
 1    13
 2    18
 3    26

Upvotes: 0

Views: 98

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

You are looking for a running total.

select C1,
       max(C2) as C2
from (
     select C1,
            sum(C2) over(order by C1 rows unbounded preceding) as C2
     from YourTable
     ) T
group by C1;

SQL Fiddle

Upvotes: 3

Related Questions