我使用此查询是为了在计算g qty_ytd
时填补漏缺的月份。
Declare @Sample Table(year int, month int, qty_ytd int);
Insert @Sample(year, month, qty_ytd) Values
(2017, 01, 20),
(2017, 02, 30),
(2018, 01, 50);
;With Months As
(Select 1 As month
Union All
Select month + 1 From Months Where month < 12),
Years As (Select Distinct year From @Sample)
Select y.year, m.month, x.qty_ytd
From Years y
Cross Join Months m
Cross Apply (Select Max(s.qty_ytd) As qty_ytd From @Sample s Where s.year = y.year And s.month <= m.month) As x
Order By year, month;
如何在原始表中添加包含QTY_ytd值的QTY列?
答案 0 :(得分:1)
尝试一下:
Declare @Sample Table(year int, month int, qty_ytd int);
Insert @Sample(year, month, qty_ytd) Values
(2017, 01, 20),
(2017, 02, 30),
(2018, 01, 50);
;With Months As
(Select 1 As month
Union All
Select month + 1 From Months Where month < 12)
, YearsAndMonths As
(Select distinct year,m.month from @Sample cross join Months m)
select ym.*, coalesce(s.qty_ytd, s2.qty_ytd) qty_ytd, coalesce(s.qty_ytd, 0) QTY from YearsAndMonths ym
left join @sample s on ym.year = s.year and ym.month = s.month
left join (select qty_ytd, year,
row_number() over (partition by year order by month desc) rn
from @Sample) s2 on ym.year = s2.year and rn = 1