Partitioning in sql to find cumulative sum based on financial year dates
running sum based in dates
sql server - Cumulative sum in sql, in case of dates - Stack Overflow
sql server - SQL - Cumulative sum in sql, base on continuous dates - Stack Overflow
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
Here's an example based on Scott's EMP table, which counts jobs per department. The last column is the "running total" value.
Sample data shows that there are 3 employees in DEPTNO = 10, 5 of them in dept. 20 and 6 in dept. 30:
SQL> select deptno, empno, ename from emp order by deptno;
DEPTNO EMPNO ENAME
---------- ---------- ----------
10 7782 CLARK
10 7839 KING
10 7934 MILLER
20 7566 JONES
20 7902 FORD
20 7876 ADAMS
20 7369 SMITH
20 7788 SCOTT
30 7521 WARD
30 7844 TURNER
30 7499 ALLEN
30 7900 JAMES
30 7698 BLAKE
30 7654 MARTIN
14 rows selected.
Query then looks like this:
SQL> select
2 deptno,
3 count(empno) emps_per_dept,
4 sum(count(*)) over (order by deptno) total
5 from emp
6 group by deptno;
DEPTNO EMPS_PER_DEPT TOTAL
---------- ------------- ----------
10 3 3
20 5 8
30 6 14
SQL>
Which, in your case, might be like this:
SELECT
...
,sum(COUNT(TKTNUM)) over (order by TO_CHAR(DTTM,'YYYY-MM-DD')) AS "TOTAL"
FROM TKTHISTORY
...
SELECT t.user_id,
t.transactions_,
SUM(t.transactions_) over(ORDER BY t.user_id) cum_sum
FROM FEBRUARY_2023_USER_ACTIVITIES t
