用给定分区中以前的非空值替换空值

gorkyyrv  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(284)

如何计算新列在哪里 NULL 值来自 Number 列是否将替换为以前的非空列?不是 NULL 那些应该保持不变。全部在分区内 Customer .

+----------+------------+--------+
| Customer |    Date    | Number |
+----------+------------+--------+
| A        | 2016-01-01 | 9,00   |
| A        | 2020-01-01 | NULL   |
| A        | 2020-01-15 | 10,00  |
| A        | 2020-02-01 | NULL   |
| A        | 2020-03-01 | NULL   |
| A        | 2020-03-15 | 11,00  |
| A        | 2020-04-01 | NULL   |
| B        | 2016-01-01 | 9,00   |
| B        | 2020-01-01 | NULL   |
| B        | 2020-01-15 | 10,00  |
| B        | 2020-02-01 | NULL   |
| B        | 2020-03-01 | NULL   |
| B        | 2020-03-15 | 11,00  |
| B        | 2020-04-01 | NULL   |
+----------+------------+--------+

假设:
输入数据为 ORDER BY Customer, Date ,输出也应如此
第一排(最老的一排) Customer 永远都有 Number 不同于 NULL

cedebl8k

cedebl8k1#

如果支持sql server,这将更容易 lag(ignore nulls) . 但事实并非如此。您可以通过对具有值的行进行累计计数,然后分散这些值来定义组:

select t.*,
       max(number) over (partition by customer, grp)
from (select t.*, count(number) over (partition by customer order by date) as grp
      from t
     ) t;

你也可以用 apply ,但我怀疑在几乎所有情况下,上述方法都更快。

hxzsmxv2

hxzsmxv22#

SELECT customer ,[date] ,case when number is null then B.number else t.number end number
    FROM yourTable t
    CROSS APPLY (
        SELECT TOP 1 number
        FROM yourTable
        WHERE customer = t.customer
            AND number IS NOT NULL
        ORDER BY DATE DESC
        ) B

相关问题