简体   繁体   English

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

[英]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 get 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. MYSQL解决方案非常简单,但简单的解决方案正在寻找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. 没有order by子句的查询没有保证顺序。 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): 所以,如果我们修复它并在表上放置一个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

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM