How can I execute this query using pure sql?

I have a table below

 first      second 
-------     ---------- 
100        0 
200        0 
0           400 

I want to get the result below

 first      second      result 
-------     ---------- ---------- 
100        0            100 
200        0            300 
0           400         -100 

As you can see, this result parameter is the sum of the previous one (first sum). How can I write such a request?

Decision

MYSQL is very simple, but simple solutions are looking for Microsoft Sql Server.

set @result =0; 
select first, second, @result := @result + first - second as result 
from tablo;  

results

first  second  result   
100    0       100  
200    0       300  
0      400     -100 
+3
source share
2 answers

Here is the version with a common table expression. He also suffers from a lack of order, so I used the second to get the desired results.

WITH cte as
    (
    select [first], [second], [first] - [second] as result,
        ROW_NUMBER() OVER (ORDER BY second, first) AS sequence
    from tableo
    )

SELECT t.[first], t.[second], SUM(t2.result) AS result
from cte t
JOIN cte t2 on t.sequence >= t2.sequence
GROUP BY t.[first], t.[second]
+3
source

, , . order by . .

, identity , , CTE ( mssql 2005 new):

with running_sum as (
  select
    t.id, t.first, t.second, t.first-t.second as result
  from
    table t where t.id = 1
  UNION ALL
  select
    t.id, t.first, t.second, r.result+t.first-t.second
  from
    table t
    join running_sum r on r.id = t.id - 1
)
select
  *
from
  running_sum
order by
  id
+4

Source: https://habr.com/ru/post/1779080/


All Articles