Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用纯sql进行此查询?_Sql_Sql Server - Fatal编程技术网

如何使用纯sql进行此查询?

如何使用纯sql进行此查询?,sql,sql-server,Sql,Sql Server,我有一张桌子在下面 first second ------- ---------- 100 0 200 0 0 400 我想得到下面的结果 first second result ------- ---------- ---------- 100 0 100 200 0 300 0 400

我有一张桌子在下面

 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 

你的第一个问题是,你在没有秩序的地方假设秩序。没有ORDERBY子句的查询没有保证的顺序。没有聚集索引的表没有定义的顺序

因此,如果我们解决了这个问题,并在表上放置一个
identity
列,这样我们就有了一个定义良好的顺序,那么您可以使用递归CTE do it(在mssql 2005和更新版本中):


这是一个带有通用表表达式的版本。它还存在缺少排序的问题,所以我使用了第二个,第一个来获得所需的结果

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]
从选项卡中选择*进入#gec;更改表格#gec添加结果浮动;声明@result float;设置@result=0;更新#gec set@result=result=@result+first second;从#gec中选择*;
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]