I Use SQL Server 2012 and have a table like below:
DECLARE @T TABLE(Id INT, [Type] CHAR(1), Quantity INT, Price MONEY, UnitPrice AS (Price/Quantity))
INSERT INTO @T VALUES
(1, 'I', 30, 1500),
(2, 'O', 5, NULL),
(3, 'O', 20, NULL),
(4, 'O', 2, NULL),
(5, 'I', 10, 2500),
(6, 'I', 8, 1000),
(7, 'O', 3, NULL),
(8, 'O', 10, NULL),
(9, 'I', 12, 3600)
In my table I have a Type Column With Values ('I' and 'O') I have unit price for 'I' Type Record and 'O' Type Record used last 'I' Type Record Value I want to calculate RunningTotalPrice (Sum of Quantity*UnitPrice of each rows).
Following code calculate RunningTotalQuantity:
SELECT *,
SUM(CASE WHEN [Type] = 'I' Then Quantity ELSE -Quantity END)OVER (ORDER BY Id) AS QuantityRunningTotal
FROM @T
and Results of this query is:
Id Type Quantity Price UnitPrice QuantityRunningTotal
1 I 30 1500/00 50/00 30
2 O 5 NULL NULL 25
3 O 20 NULL NULL 5
4 O 2 NULL NULL 3
5 I 10 2500/00 250/00 13
6 I 8 1000/00 125/00 21
7 O 3 NULL NULL 18
8 O 10 NULL NULL 8
9 I 12 3600/00 300/00 20
I want to have following Result
Id Type Quantity Price UnitPrice QuantityRunningTotal Price RunningTotalPrice
1 I 30 1500/00 50/00 30 1500/00 1500/00
2 O 5 NULL 50/00 25 250/00 1250/00
3 O 20 NULL 50/00 5 1000/00 250/00
4 O 2 NULL 50/00 3 100/00 150/00
5 I 10 2500/00 250/00 13 2500/00 2650/00
6 I 8 1000/00 125/00 21 1000/00 3650/00
7 O 3 NULL 125/00 18 375/00 3275/00
8 O 10 NULL 125/00 8 1250/00 2025/00
9 I 12 3600/00 300/00 20 3600/00 5625/00
In this result Null Unitprice Column valued with last exists unitprice in before records. and Calculate Price ( Quantity * UnitPrice) and The Calculate Running Total Of Price.
Pricecolumn