在 SQL 服务器中使用递归 CTE 填充缺失的行
Fill missing rows using RECURSIVE CTE in SQL SERVER
输入
id, date, value
1, '2020-01-01', 100
1, '2020-01-03', 200
1, '2020-01-05', 500
预期输出
1, '2020-01-01', 100
1, '2020-01-02', 100
1, '2020-01-03', 200
1, '2020-01-04', 200
1, '2020-01-05', 500
我不想使用与此一起加入的任何日历 table。
我想用递归 CTE
来实现
示例数据
create table data
(
d date,
i int
);
insert into data (d, i) values
('2020-01-01', 100),
('2020-01-03', 200),
('2020-01-05', 500);
解决方案
with maxDate as
(
select max(d.d) as maxDate
from data d
),
rcte as
(
select d.d, d.i
from data d
union all
select dateadd(day, 1, r.d), r.i
from rcte r
cross join maxDate md
where r.d < md.maxDate
)
select '1' as [id],
r.d as [date],
max(r.i) as [value]
from rcte r
group by r.d
order by r.d;
结果
id date value
--- ----------- -----
1 2020-01-01 100
1 2020-01-02 100
1 2020-01-03 200
1 2020-01-04 200
1 2020-01-05 500
输入
id, date, value
1, '2020-01-01', 100
1, '2020-01-03', 200
1, '2020-01-05', 500
预期输出
1, '2020-01-01', 100
1, '2020-01-02', 100
1, '2020-01-03', 200
1, '2020-01-04', 200
1, '2020-01-05', 500
我不想使用与此一起加入的任何日历 table。 我想用递归 CTE
来实现示例数据
create table data
(
d date,
i int
);
insert into data (d, i) values
('2020-01-01', 100),
('2020-01-03', 200),
('2020-01-05', 500);
解决方案
with maxDate as
(
select max(d.d) as maxDate
from data d
),
rcte as
(
select d.d, d.i
from data d
union all
select dateadd(day, 1, r.d), r.i
from rcte r
cross join maxDate md
where r.d < md.maxDate
)
select '1' as [id],
r.d as [date],
max(r.i) as [value]
from rcte r
group by r.d
order by r.d;
结果
id date value
--- ----------- -----
1 2020-01-01 100
1 2020-01-02 100
1 2020-01-03 200
1 2020-01-04 200
1 2020-01-05 500