sql – 每年从零开始的累积列

我的数据从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

最佳答案 使用窗口函数SUM有一种更好的方法

select Date,
    sum(sum(DailyValue)) over (
        partition by year(date) order by date
        ) as cumul
from Ratio
group by Date
order by Date;
点赞