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

Check one of methods:
;
with Q1 as
(
select *, case when Date > dateadd(month, 1, lag(Date) over ( partition by PRODUCT order by Date)) then Date end as f
from MyTable
),
Q2 as
(
select *, max(f) over ( partition by PRODUCT order by Date) m
from Q1
)
select PRODUCT, Date, price, sum(price) over ( partition by PRODUCT, m order by Date) Total
from Q2
order by PRODUCT, Date
Hi @AbdulWahab Khan
Please also check this:
;WITH CTE1 AS
(
SELECT *,DATEDIFF(DAY,LAG(MyDate,1,MyDate)OVER(ORDER BY MyDate),MyDate) AS Date_Diff
FROM #Your_Table
),CTE2 AS
(
SELECT *,SUM(Date_Diff/31)OVER(PARTITION BY PRODUCT ORDER BY MyDate)AS PART
FROM CTE1
)
SELECT PRODUCT,MyDate,price, SUM(price)OVER(PARTITION BY PRODUCT,PART ORDER BY MyDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)AS Total
FROM CTE2
Best regards,
LiHong