我有一个类似下面的表格:
declare @test table(Aid int, Bid int, CheckMonth date, Avalue decimal(18,2))
insert into @test (Aid, Bid, CheckMonth, Avalue)
values (1, 4, '2014-07-05', 123.00)
,(1, 4, '2014-08-01', 467.00)
,(1, 4, '2014-11-03', 876.00)
,(1, 4, '2014-12-01', 876.00)
,(2, 6, '2016-01-02', 23.00)
,(2, 6, '2016-03-14', 56.00)
,(2, 6, '2016-04-17', 98.00)
,(2, 6, '2016-07-01', 90.00)
我希望用0.00值(在Avalue列中)填补月份(在上面的CheckMonth列中)的空白。数据按“援助”和“出价”列分组。
结果应如下图所示:
Aid Bid CheckMonth Avalue
1 4 '2014-07-05' 123.00
1 4 '2014-08-01' 467.00
1 4 '2014-09-01' 0.00 -->inserted
1 4 '2014-10-01' 0.00 -->inserted
1 4 '2014-11-03' 876.00
1 4 '2014-12-01' 876.00
2 6 '2016-01-02' 23.00
2 6 '2016-02-01' 0.00 -->inserted
2 6 '2016-03-14' 56.00
2 6 '2016-04-17' 98.00
2 6 '2016-05-01' 0.00 -->inserted
2 6 '2016-06-01' 0.00 -->inserted
2 6 '2016-07-01' 90.00
感谢您的帮助。谢谢。
[一个选项使用递归查询为每个(aid, bid)
元组生成月份开始;然后可以用原始表来left join
生成的结果集:
with cte as (
select
aid,
bid,
datefromparts(year(min(checkMonth)), month(min(checkMonth)), 1) dt,
datefromparts(year(max(checkMonth)), month(max(checkMonth)), 1) maxDt
from @test
group by aid, bid
union all
select
aid,
bid,
dateadd(month, 1, dt),
maxDt
from cte
where dt < maxDt
)
select c.aid, c.bid, coalesce(t.checkMonth, c.dt) checkMonth, coalesce(t.avalue, 0) avalue
from cte c
left join @test t
on t.aid = c.aid
and t.bid = c.bid
and t.checkMonth >= c.dt
and t.checkMonth < dateadd(month, 1, c.dt)
order by c.aid, c.bid, c.dt
援助|出价| checkMonth |一个值-:| -:| :--------- | :-----1 | 4 | 2014-07-05 | 123.001 | 4 | 2014-08-01 | 467.001 | 4 | 2014-09-01 | 0.001 | 4 | 2014-10-01 | 0.001 | 4 | 2014-11-03 | 876.001 | 4 | 2014-12-01 | 876.002 | 6 | 2016-01-02 | 23.002 | 6 | 2016-02-01 | 0.002 | 6 | 2016-03-14 | 56.002 | 6 | 2016-04-17 | 98.002 | 6 | 2016-05-01 | 0.002 | 6 | 2016-06-01 | 0.002 | 6 | 2016-07-01 | 90.00