取得年初至今

时间:2020-01-08 03:08:31

标签: sql sql-server tsql

我在下表中有数据。

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。我该怎么办?

1 个答案:

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

Demo on DB Fiddlde

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