红移SQL-插补缺失值:修改仅在状态更改为具有每日数据时存储数据的表
假设我有一张像下面这样的桌子红移SQL-插补缺失值:修改仅在状态更改为具有每日数据时存储数据的表,sql,amazon-web-services,amazon-redshift,Sql,Amazon Web Services,Amazon Redshift,假设我有一张像下面这样的桌子 ID Status Date A1 S1 1/1/2021 A1 S2 1/4/2021 B1 S1 1/1/2021 B1 S2 1/3/2021 我希望我的最后一张桌子是什么样的 ID Status Date A1 S1 1/1/2021 A1 S1 1/2/2021 --On 1/2, status remained the same as 1/1 A1 S1 1/3
ID Status Date
A1 S1 1/1/2021
A1 S2 1/4/2021
B1 S1 1/1/2021
B1 S2 1/3/2021
我希望我的最后一张桌子是什么样的
ID Status Date
A1 S1 1/1/2021
A1 S1 1/2/2021 --On 1/2, status remained the same as 1/1
A1 S1 1/3/2021 --On 1/3, status remained the same as 1/2
A1 S2 1/4/2021 --Status changed
B1 S1 1/1/2021
B1 S1 1/2/2021
B1 S2 1/3/2021
B1 S2 1/4/2021
如何编写SQL查询来实现这一点
如果我的桌子是这样的,我怎么能估算那些缺失的呢
ID Status Date
A1 S1 1/1/2021
A1 NULL 1/2/2021
A1 NULL 1/3/2021
A1 S2 1/4/2021
B1 S1 1/1/2021
B1 NULL 1/2/2021
B1 S2 1/3/2021
B1 NULL 1/4/2021
谢谢 如果您有日历表,可以执行以下操作:
select i.id, c.date, t.status,
coalesce(t.status, lag(t.status ignore nulls) over (partition by i.id order by c.date) as imputed_status
from (select distinct id from t) i cross join
calendar c left join
t
on t.id = i.id and t.date = c.date
where c.date between '2021-01-01' and '2021-01-04'
order by i.id, c.date;
你们有日历表还是理货表?用红移生成日期有问题。@GordonLinoff是的,我有一个日历表