running sum based in dates
Partitioning in sql to find cumulative sum based on financial year dates
sql server - How to get cumulative sum - Stack Overflow
Creating a Cumulative Total by Date
Hi everyone! Would anyone have any recommendations around the following?
I am working in the sql Microsoft sql server management tool.
Date in the database is in the form 2026-10-21. There are many different dates across many different years.
I have a sql code already written however I am wanting to do a cumulative sum based also off financial year. So from 1/July/2026(thatyear) to 30/June/2027. Basically if data falls within this range it will be summed with other data within this range.
Code:
Select Prod.Electro.*, Ap.Proj.id, Ap.Proj.name,
, Sum(production) OVER (PARTITION BY proj_id ORDER BY date, proj_id) as Cumulative_sum
FROM Prod.Electro
LEFT JOIN Ap.Proj ON Prod.Electro.project_id = Ap.Proj.id
The latest version of SQL Server (2012) permits the following.
SELECT
RowID,
Col1,
SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId
or
SELECT
GroupID,
RowID,
Col1,
SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId
This is even faster. Partitioned version completes in 34 seconds over 5 million rows for me.
Thanks to Peso, who commented on the SQL Team thread referred to in another answer.
select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id
SQL Fiddle example
Output
| ID | SOMENUMT | SUM |
-----------------------
| 1 | 10 | 10 |
| 2 | 12 | 22 |
| 3 | 3 | 25 |
| 4 | 15 | 40 |
| 5 | 23 | 63 |
Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!