计算年初至今

时间:2019-05-20 14:55:32

标签: sql sql-server

我有一张表迄今为止的累计年份

year month qty_ytd
2017   01    20
2017   02   30
2018   01    50

我需要在同年12月之前填补缺失的月份:

结果示例:

year month qty_ytd
2017   01    20
2017   02   30
2017   03   30
.....
2017   07   30
2017   12   30

2018   01    50
2018   02    50
....
2018   12    50

该怎么做?我没有弄清楚如何填补缺失的月份?

2 个答案:

答案 0 :(得分:1)

您可以使用long_word = "juxtaposition" location = long_word.find("t") print(long_word[location+1:]) second_location = long_word[location+1:].find("t") print(second_location) print(long_word[location:location+second_location+2]) 来生成行,并使用cross join来获取数据:

cross apply

假设select y.y, v.m, t.qty_ytd from (select distinct year from t) y cross join (values (1), (2), (3), (4), . . . (12)) v(m) outer apply (select top (1) t.* from t where t.year = y.year and t.month <= y.m order by t.m desc ) t; 不变,那么使用窗口函数可能会更有效:

qty_ytd

答案 1 :(得分:1)

另一种选择是计算增量,添加虚拟零增量,恢复运行总计。我已更改源数据以显示更常见的情况

create table #t
(
 year int,
 month int, 
 qty_ytd int
);

insert #t(year, month, qty_ytd )
values
(2017,   01,   20),
(2017,   02,   30),
(2018,   04,   50) -- note month
;

select distinct year, month, sum(delta) over(partition by year order by  month)
from (
    -- real delta
    select year, month, delta = qty_ytd - isnull(lag(qty_ytd) over (partition by year order by month),0)
    from #t
    union all
    -- tally dummy delta
    select top(24) 2017 + (n-1)/12, n%12 + 1 , 0
    from 
    ( select row_number() over(order by a.n) n
      from
      (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) a(n),
      (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) b(n)
    ) c
)d
order by year, month;