我怎样才能通过纯sql进行此查询?

时间:2010-12-07 23:45:16

标签: sql sql-server

我有一张桌子

 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 

2 个答案:

答案 0 :(得分:4)

你的第一个问题是你假设订单没有。没有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

答案 1 :(得分:3)

这是一个带有公用表表达式的版本。它也受到缺乏排序问题的困扰,因此我使用了第二个,首先得到了预期的结果。

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]
相关问题