0. 题目
根据value数据原表补充缺失数据,如果当月value数据没有则取上月填充
输入表
month | value |
---|---|
1 | 200 |
2 | null |
3 | null |
4 | 600 |
5 | null |
目标表预期结果
month | value |
---|---|
1 | 200 |
2 | 200 |
3 | 200 |
4 | 600 |
5 | 600 |
1、gaps-and-islands
这类问题被称为gaps-and-islands (间隙与孤岛),
将行拆分为“组”其中每个组中只有第一行为NOT NULL,再赋值 。
使用开窗函数 lead,lead :形象的理解就是把数据从下向上推,下端出现空格。
with t as (
select month as from_month,
lead(month,1, (select max(month) from table) +1)
over (order by month ) -1 as to_month,
汇率
where 汇率 is not null), —t表先找到每组中not null的值,并确定每组的范围
result as (
select raw.month ,t.汇率
from table raw,t
where raw.汇率 is null and (raw.month between t.from_month and t.to_month) --给null的行赋值
union all --上面给null行赋值操作排除了not null行,这里union回来
select month ,汇率 where 汇率 is not null)
select * from result order by month
也可以用cte递归写法,待补充