计算累计总和时添加列

时间:2019-05-21 08:23:20

标签: sql sql-server tsql sql-server-2008-r2

我使用此查询是为了在计算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;

enter image description here

如何在原始表中添加包含QTY_ytd值的QTY列?

enter image description here

1 个答案:

答案 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