Cumulative column starting at zero every year

I have data from January 1, 2008 to date, sorted by date in the first column of the Ratio table.

I have values ​​in the second column. I was able to make a cumulative third column with the following code, but I don’t know how to make it restart every January 1 to have a cumulative volume per year.

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
+4
source share
1 answer

There is a better way to use a window function SUM

select Date,
    sum(sum(DailyValue)) over (
        partition by year(date) order by date
        ) as cumul
from Ratio
group by Date
order by Date;
+3
source

Source: https://habr.com/ru/post/1677119/


All Articles