每年每月的SQL YTD

时间:2018-05-09 01:42:20

标签: sql tsql sql-server-2014

我有下表:

oDate        oValue
----------------------------
2017-01-01   40
2017-02-01   50
2017-03-01   60
2017-04-01   10

每个月只有一个数据 然后,我想得到以下结果:

oDate        oValue         YTD
----------------------------------------
2017-01-01   40             40
2017-02-01   50             90
2017-03-01   60             150
2017-04-01   10             160

因此,YTD值是上个月oValue的总和,并且将在选定年份的12月结束。当新Year开始时,它将再次计算,忽略前一年。

有没有人有这个想法?
谢谢。

2 个答案:

答案 0 :(得分:1)

只需使用运行总和功能:

select odate, ovalue,
       sum(ovalue) over (partition by year(odate) order by odate) as ytd
from t;

这是一个窗口功能。 partition by每年重新开始计算金额。 order by执行一年内的累计金额。

答案 1 :(得分:0)

一个选项使用相关子查询来查找累计总数:

SELECT
    t1.oDate,
    t1.oValue,
    (SELECT SUM(t2.oValue) FROM yourTable t2
     WHERE t2.oDate <= t1.oDate AND YEAR(t1.oDate) = YEAR(t2.oDate)) AS YTD
FROM yourTable t1
ORDER BY t1.oDate;

enter image description here

Demo