簡體   English   中英

我怎樣才能通過純sql進行此查詢?

[英]How can i do this query by pure sql?

我有一張桌子

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

我想得到低於結果

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

正如您所看到的那樣,結果參數是之前的總和(第一次總和)如何編寫這樣的查詢?

MYSQL解決方案非常簡單,但簡單的解決方案正在尋找Microsoft Sql Server。

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

結果

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

你的第一個問題是你假設訂單沒有。 沒有order by子句的查詢沒有保證順序。 沒有聚簇索引的表沒有已定義的順序。

所以,如果我們修復它並在表上放置一個identity列,以便我們確實有一個定義良好的順序,你可以使用遞歸CTE(在mssql 2005和更新版本中):

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

這是一個帶有公用表表達式的版本。 它也受到缺乏排序問題的困擾,所以我使用了第二個,首先得到了預期的結果。

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM