sql - 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
解决方案
由于源表中缺少排序列,它将动态创建。查询的其他部分取决于该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注意添加到原始样本数据中的额外行。
推荐阅读
- python - Windows 中 wlan 的 Subprocess.check_output 的 CalledProcessError
- php - PHP 上的 MySQL 需要 2 次重新加载来更新值
- android - 数据库更改时 UI 不更新
- python - MacBook:操作系统更新后无法启动 jupyter notebook
- ffmpeg - 下载youtube视频时ffmpeg“清单太大”
- python - 在 Python 中计算子网的地址
- python - 如何从生成的列表数据中制作熊猫数据框
- excel - 如何在 VBA excel 中添加上传附件按钮
- sql - 在 oracle 中处理不同的逗号分隔值
- python - 我有一个应该与 html 代码一起使用的 python 代码。确认按钮不起作用。我将把代码放在下面