Thursday, February 4, 2021

SQL15 Commulative SUM of Sales

Data is given table, we have date along with the sales. We need to calculate commulative sum for all the sales

below are the various ways to perform this task

Data in Table 

Year Sales
2019-09-01 10
2019-10-01 60
2019-11-01 20
2019-12-01 10
2020-01-01 30
2020-02-01 20
2020-03-01 80
2021-01-01 70
2021-02-01 30
2021-03-01 10
Expected Result
year salesSum_sales
2019-09-01 10 10
2019-10-01 60 70
2019-11-01 20 90
2019-12-01 10 100
2020-01-01 30 130
2020-02-01 20 150
2020-03-01 80 230
2021-01-01 70 300
2021-02-01 30 330
2021-03-01 10 340
SELECT *
INTO SQL15
FROM (
	SELECT '2019-09-01' AS MONTH
		, 10 AS SALES
	
	UNION ALL
	
	SELECT '2019-10-01' AS MONTH
		, 60 AS SALES
	
	UNION ALL
	
	SELECT '2019-11-01' AS MONTH
		, 20 AS SALES
	
	UNION ALL
	
	SELECT '2019-12-01' AS MONTH
		, 10 AS SALES
	
	UNION ALL
	
	SELECT '2020-01-01' AS MONTH
		, 30 AS SALES
	
	UNION ALL
	
	SELECT '2020-02-01' AS MONTH
		, 20 AS SALES
	
	UNION ALL
	
	SELECT '2020-03-01' AS MONTH
		, 80 AS SALES
	
	UNION ALL
	
	SELECT '2021-01-01' AS MONTH
		, 70 AS SALES
	
	UNION ALL
	
	SELECT '2021-02-01' AS MONTH
		, 30 AS SALES
	
	UNION ALL
	
	SELECT '2021-03-01' AS MONTH
		, 10 AS SALES
	) t

SELECT t1.month
	, year(t1.month)
	, t1.sales
	, sum(t2.sales)
FROM sql15 t1
JOIN sql15 t2 ON (t1.month) >= (t2.month)
GROUP BY t1.month
	, t1.sales
	, year(t1.month)
ORDER BY 1
	, 2

Releated post - SQL 14 (Click Here)

Tags- SQL Excercise, Requirement solution, Practice, Query Logic, Assignments, SQL Practice

No comments:

Post a Comment

web stats