sql - SQL Server 将第一列数据放在所有行中,直到下一行有一些值
问题描述
我有一个需要根据逻辑取消分组的数据列表,例如需要将同一列数据放置在所有行中,直到下一行具有某些值。
A | NULL
NULL | 1
NULL | 2
NULL | 3
B | NULL
NULL | 4
NULL | 5
我需要返回结果,例如:
A | 1
A | 2
A | 3
B | 4
B | 5
因此,基本上第一列中的所有空值都需要用不为空的前一行第一列数据填充。
谢谢您的帮助。
解决方案
假设您有一个排序列,然后使用您的样本数据,您可以使用累积最大值:
select max(col1) over (order by <order col>) as col1,
max(col2) over (order by <order col>) as col2
from t;
max()
实际上可能不是正确的功能——因为假数据可能恰好在增加。如果是这种情况,您可以改为:
select max(col1) over (partition by oc_col1) as col1,
max(col2) over (partition by oc_col2) as col2
from (select t.*,
max(case when col1 is not null then <order col> end) over (order by <order col>) as oc_col1,
max(case when col2 is not null then <order col> end) over (order by <order col>) as oc_col2
from t
) t;
你真正想要的是lag(ignore nulls)
。但是,SQL Server(尚)不支持该(标准)功能。
编辑:
NULL
您可以在开头轻松处理单个值:
select max(col1) over (order by id) as col1,
coalesce(max(col2) over (order by id),
min(col2) over () - 1
) as col2
from t;
这是你的 db<>fiddle。
推荐阅读
- celery - 如何禁用芹菜任务结果记录?
- r - 如何将列表元素提取到 r 中的多个 tibble 列中?
- python - 组内的 Python 排列
- python - 迭代列表并查看元素是否存在的最快方法?
- php - 限制 PHP 仅在实际文件夹和子文件夹中运行
- javascript - 为什么 useEffect 挂钩在 DOM 加载之前运行?
- listview - Flutter - 在Android上将项目添加到列表后ListView没有更新
- kubernetes - 输入字节 8 处的非法 base64 数据
- python - 使用反斜杠 Jsonify 响应数据
- c# - Blazor 从 Child 获取 Parent ModelType 进行反射