首页 > 解决方案 > SQL查询根据前几行计算表

问题描述

我需要一个查询来将表从选项卡 A 转换为表 B:我使用了像 Lag 这样的窗口函数,但它无法帮助表 1:

Concat_date_hour 类型 价值 Next_Movement
2021092414 D 16923 63
2021092415 D 0 149
2021092415 D 0 -56
2021092415 D 0 -131
2021092415 D 0 -79

输出表:

Concat_date_hour 类型 实际价值 新价值
2021092414 D 16923 16986
2021092415 D 16986 17135
2021092415 D 17135 17079
2021092415 D 17079 16948
2021092415 D 16948 16869

PS类型可以不同于D

标签: sqlsql-server

解决方案


由于源表中缺少排序列,它将动态创建。查询的其他部分取决于该rn任意排序列。

select Concat_date_hour, Type,
  --rn, Value, Next_Movement, 
  rt - Next_Movement actual, rt [new value]
from (
  select *, sum(Value + Next_Movement) over (partition by Type order by Concat_date_hour, rn) rt
  from (
     select  *, row_number() over(partition by Type, Concat_date_hour order by Concat_date_hour) rn
     from tbl ) t
) t
order by Type, Concat_date_hour, rn;

db<>fiddle注意添加到原始样本数据中的额外行。


推荐阅读