This article is half-done without your Comment! *** Please share your thoughts via Comment ***
The SQL Server 2012 also introduced UNBOUNDED option using PRECEDING and FOLLOWING options.
The UNBOUNDED option is very useful to determine a calculation from the beginning of a set to the current row, or from the current row to the end of a set or group.
We can calculate the cumulative SUM column with the many different options like: CTE, Self join, but in this post I am using UNBOUNDED PRECEDING option of SQL Server 2012.
For example, If we are working with sales and inventory management domain, every day we require to calculate cumulative sum of different columns like: stock value, profit figure, expense figure.
Generally, we can use this kind of demonstration for report purpose only and if it is required to store, we can populate and store for permanent use.
Below is a small demonstration to calculate Cumulative SUM column.
First, create sample table with data:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
CREATE TABLE tbl_SampleSum ( ID INT ,SumValue INT ) GO INSERT INTO tbl_SampleSum VALUES (1,100),(2,150),(3,175) ,(4,250),(5,100),(6,88) ,(7,120),(8,130),(9,275) GO |
Populate cumulative SUM column using UNBOUNDED PRECEDING:
1 2 3 4 5 6 |
SELECT ID ,SumValue ,SUM(SumValue) OVER(ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS CumulativeSum FROM tbl_SampleSum ORDER BY ID |
The Result:
1 2 3 4 5 6 7 8 9 10 11 |
ID SumValue CumulativeSum ----------- ----------- ------------- 1 100 100 2 150 250 3 175 425 4 250 675 5 100 775 6 88 863 7 120 983 8 130 1113 9 275 1388 |
Leave a Reply