繁体   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