每年从零开始的累计列

时间:2017-05-14 17:43:25

标签: sql sql-server

我的数据从2008年1月1日到今天按日期排列在表比率的第一列。

我在第二列中有值。我能够使用以下代码执行累积的第三列,但我不知道如何使其每年1月1日重新开始,以便每年累计。

SELECT 
    t3.Date, 
    SUM(cumul) AS cumul 
FROM (
    SELECT 
        t1.Date, 
        t1.nb, 
        SUM(t2.nb) AS cumul   
    FROM (
        SELECT 
            Ratio.Date, 
            SUM(DailyValue) AS Nb
        FROM Ratio
        GROUP BY Ratio.Date
    )t1
    INNER JOIN (
        SELECT 
            Ratio.Date, 
            SUM(DailyValue) AS nb
        FROM Ratio
        GROUP BY Ratio.Date
    ) t2 
        ON t1.Date >= t2.Date
    GROUP BY t1.Date, t1.nb
)t3
GROUP BY PnLDate,nb
ORDER BY pnldate

1 个答案:

答案 0 :(得分:2)

使用窗口函数SUM

有一种更好的方法
select Date,
    sum(sum(DailyValue)) over (
        partition by year(date) order by date
        ) as cumul
from Ratio
group by Date
order by Date;