Search code examples
sqldatabasesumwindow-functionscumulative-sum

Struggling with Running Sum query in SQL


I am struggling with this query. It is calculating the running sum correctly for the first depot but as soon as it gets to the next depot it should start at zero again for the running sum total but it continues with the previous depot's ending total, what am I doing wrong?

Here is my query, I've also added an image of the output.

SELECT 
    Depot
    ,WorkDayNr
    ,DayOfMonth
    ,Tons
    ,SUM (Tons) OVER (ORDER BY Depot, WorkDayNr) AS RunTotal
FROM #Final
GROUP BY Depot, WorkDayNr, DayOfMonth, Tons
ORDER BY Depot, WorkDayNr

run


Solution

  • Add partition clause:

     SUM (Tons) OVER (PARTITION BY SUBGROUP ORDER BY Depot, WorkDayNr) AS RunTotal