Running Sum in SQL Server
As a Programmer\developer we are aware of Fibonacci Sequence where the next number is found by adding up the two numbers before it.
for e.g.-0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
In SQL we termed it as Running Total or RunningSum where we will add a new Column that will calculate the Running total.
CREATE TABLE RunningTotal (
Product nvarchar(100),
P_Cost int not null
)
INSERT INTO RunningTotal (Product,P_Cost) VALUES ('X',100),('X',150),('X',200),('X',250),('X',300);
INSERT INTO RunningTotal (Product,P_Cost) VALUES ('Y',1000),('Y',1500),('Y',2000),('Y',2500),('Y',3000);
INSERT INTO RunningTotal (Product,P_Cost) VALUES ('Z',10),('Z',15),('Z',20),('Z',25),('Z',30);
So below is the Script calculating Running Sum (Fibonacci Sequence in a New Column ) and Running Sum Per Product.
Below Script will calculate two below Columns
- Total Running Sum-Running Total of P_cost for all Product irrespective of Product
- Running Sum Per Product-Running Total of each Product Calculating Running Sum for Each Product
(
Select Product,P_cost,row_number()over(order by (Select 0))as RowNum
from RunningTotal b
)
select Product,P_cost ,(Select Sum(P_cost) as TotalRunningSum from cte a where a.RowNum<=b.rownum ) as TotalRunningSum,
(Select Sum(P_cost) as TotalRunningSum from cte a where a.RowNum<=b.rownum and a.Product=b.product ) as RunningSumPerProduct
from cte b
order by Product
Output
No comments:
Post a Comment