开发者

How can i do this query by pure sql?

I have a table below

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

I want to g开发者_Python百科et below result

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

As you can see that result parameter is sum of previous (first-sum) How can i write such a query ?

MYSQL solution 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 


Your first problem is that you're assuming order where there is none. A query without an order by clause has no guaranteed order. Tables without a clustered index don't have a defined order.

So, if we fix that and put an identity column on the table so that we do have a well defined order, you can use a recursive CTE do it (in mssql 2005 and newer):

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


Here's a version with a common table expression. It also suffers from the lack-of-ordering issue, so I used second, first 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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜