Click here to Skip to main content
15,905,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote following query to get the result shown in below table
SQL
SELECT EOMONTH (ADateTime) ADateTime, 
				CAST (SUM(ISNULL(Profit,0)) AS decimal(18,3)) Profit
				FROM CostLedger
				WHERE ISNULL(Profit,0)>0 AND YEAR(ADatetime)=YEAR(CAST ( '2017-May-01' as Date))
				GROUP BY  EOMONTH (ADateTime)


RESULTS
ADateTime	Profit
2017-03-31	17.386
2017-04-30	180.194
2017-05-31	158.983
2017-06-30	915.255


I need to get the aggregate sum in each row as like

ADateTime  Profit          Total_Profit
2017-03-31	17.386	        17.386
2017-04-30	180.194	        197.58  (Added Previous Row Profit with Current Row)
2017-05-31	158.983	        356.563
2017-06-30	915.255	        1271.818


Any Help....to rewrite my script?

What I have tried:

SQL
SELECT EOMONTH (ADateTime) ADateTime, 
				CAST (SUM(ISNULL(Profit,0)) AS decimal(18,3)) Profit
				FROM CostLedger
				WHERE ISNULL(Profit,0)>0 AND YEAR(ADatetime)=YEAR(CAST ( '2017-May-01' as Date))
				GROUP BY  EOMONTH (ADateTime)


to get the first table result
Posted
Updated 7-Jun-17 23:32pm

1 solution

Depends on the version of SQL you are using. For SQL 2012 and later try:
SQL
SELECT a.ADateTime, a.Profit,
       SUM(Profit) OVER(ORDER BY EOMONTH(ADateTime)
           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
           AS Balance
FROM (SELECT EOMONTH (ADateTime) ADateTime, 
			 CAST (SUM(ISNULL(Profit,0)) AS decimal(18,3)) Profit
	  FROM CostLedger
	  WHERE ISNULL(Profit,0)>0 AND YEAR(ADatetime)=YEAR(CAST ( '2017-May-01' as Date))
	  GROUP BY  EOMONTH (ADateTime)) a
 
Share this answer
 
Comments
Sadique KT 8-Jun-17 5:35am    
Thanks ; Thats worked for me...
OriginalGriff 8-Jun-17 6:04am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900