SQL - 根据同一列

时间:2017-04-29 11:11:17

标签: sql

我花了好几个小时尝试用循环来解决这个问题,但滞后函数并没有解决我的问题。我有一个表格,其中填充了特定字段的第一行,下一行是基于从2列减去前一行数据计算的,然后下一行基于此结果。该示例位于原始表和结果集的下方:

   a      b         a       b   
 502.5  33.85     502.5   33.85 
        25.46     468.65  25.46 
        20.83     443.19  20.83 
        133.07    422.36  133.07
        144.65    289.29  144.65
        144.65    144.64  144.65

我已经尝试了几种不同的存储过程方法,并且可以获得第二行结果集但是我无法继续并计算其余字段,这在Excel中很容易,但在SQL中则不然。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

如果您的RDBMS支持窗口聚合函数:

假设您有Showing all 4 rows或某些确定行顺序的事情(正如您所指出的那样)。

您可以使用id(在这种情况下max() over()代替min()而不是max())和sum() over()窗口聚合函数

select 
    id 
  , max(a) over (order by id) - (sum(b) over (order by id) - b) as a
  , b
from t

rextester演示:http://rextester.com/MGKM17497

返回:

+----+--------+--------+
| id |   a    |   b    |
+----+--------+--------+
|  1 | 502,50 | 33,85  |
|  2 | 468,65 | 25,46  |
|  3 | 443,19 | 20,83  |
|  4 | 422,36 | 133,07 |
|  5 | 289,29 | 144,65 |
|  6 | 144,64 | 144,65 |
+----+--------+--------+

答案 1 :(得分:0)

如果我在编辑前看到数据的话

此解决方案还假设您有id列,订单取决于此列

with t(id, a, b) as(
    select 1, 502.5,  33.85 union all
    select 2, 25.46,  null union all
    select 3, 20.83,  null union all
    select 4, 133.07, null union all
    select 5, 144.65, null union all
    select 6, 144.65, null  
)

select case when id = 1 then a else b end as a, case when id = 1 then (select b from t order by id offset 0 rows fetch next 1 rows only) else a end as b from (
    select id, a, lag((select a from t order by id offset 0 rows fetch next 1 rows only)-s) over(order by id) as b from (
        select id, a, sum(case when b is null then a else b end  ) over(order by id) s
        from t
    ) tt
) ttt