我在下表中有数据。
Company period sales
-------------------------
a 2018-01-01 21
a 2018-02-01 22
a 2018-03-01 23
b 2018-01-01 24
b 2018-02-01 25
b 2018-03-01 26
我想要的输出如下:
comp year month YTD values MTD values
---------------------------------------------------------------------------
a 2018 jan <sum of sales in jan 2018> <sum of sales in jan 2018>
a 2018 feb <sum of sales in jan+feb 2018> <sum of sales in feb 2018>
依次类推。
我尝试使用以下查询:
SELECT Company
,month(period)
,sum(sales) AS MTD
FROM tablea
WHERE datediff(year, period, getdate()) = 0
GROUP BY month(period)
,company
ORDER BY company
,month(period)
在这里,我正确地获得了mtd
的值,但是我还想添加一个新列YTD
,该列为cumulative sum or running total
。我该怎么办?
答案 0 :(得分:2)
您可以使用聚合和窗口函数:
select
company,
year(period) yr,
month(period) mn,
sum(sales) mtd,
sum(sum(sales)) over(partition by company, year(period) order by month(period)) ytd
from tablea
group by
company,
year(period),
month(period)
order by
company,
year(period),
month(period)
company | yr | mn | mtd | ytd :------ | ---: | -: | --: | --: a | 2018 | 1 | 21 | 21 a | 2018 | 2 | 22 | 43 a | 2018 | 3 | 23 | 66 b | 2018 | 1 | 24 | 24 b | 2018 | 2 | 25 | 49 b | 2018 | 3 | 26 | 75