首页 > 解决方案 > 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

因此,基本上第一列中的所有空值都需要用不为空的前一行第一列数据填充。

SQL小提琴

谢谢您的帮助。

标签: sqlsql-server

解决方案


假设您有一个排序列,然后使用您的样本数据,您可以使用累积最大值:

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。


推荐阅读