【发布时间】:2020-08-23 09:08:52
【问题描述】:
我有一个如下表:
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 列分组。
结果应如下所示:
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
感谢任何帮助。 谢谢。
【问题讨论】:
-
你试过什么?你在哪里卡住了。
-
@DaleK,我尝试为组创建行号和计数,但它仅适用于一个间隙。间隔超过几个月就不行了
-
请给我们看!
-
@DaleK,我最初有这个解决方案 使用 FinalData 作为 (select Aid,Bid,CheckMonth,Avalue ,row_number() over(partition by Aid, Bid order by Aid, Bid, CheckMonth) as rowNum , count(*) over(partition by Aid, Bid) as cnt from test) select Aid,Bid,CheckMonth,Avalue from test union select t1.Aid,t1.Bid,dateadd(month, 1, t1.CheckMonth) CheckMonth,0.00从 FinalData t1 左加入 FinalData t2 on t1.rowNum + 1 = t2.rowNum 和 datediff(month, t1.CheckMonth, t2.CheckMonth) in(0,1) 和 t1.Aid = t2.Aid 和 t1.Bid = t2 .Bid 其中 t2.rowNum 为空且 t1.rowNum t1.cnt
-
@DaleK,抱歉格式化。我无法在评论中格式化上述代码
标签: sql-server tsql date sql-server-2014 recursive-query