SQL YTD 每年每个月

SQL YTD on each Month per Year

我有以下 table:

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开始时,将忽略前一年重新计算。

有人对此有想法吗?
谢谢。

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

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;

Demo

只需使用 运行 求和功能:

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

这是一个window函数。 partition by 每年重新开始求和。 order by做年内累计。