How do I show a running total from the previous records?
-
13-03-2021 - |
Question
I wonder if someone can please assist.
I have the following code which basically inserts 10 records into a table. From this table I'm trying to show a running total for the amount of sales against the seller. I've tried using the LAG function but that does not appear to work.
Here is the code.
CREATE TABLE Sales
(
OrderId Int NOT NULL,
Seller varchar(10) NULL,
Amount money NULL
)
INSERT INTO Sales VALUES
(1, 'Alex', 10.00),
(2, 'Sarah', 15.00),
(3, 'Tracy', 10.25),
(4, 'Pete', 10.25),
(5, 'Tracy', 11.00),
(6, 'Tracy', 10.25),
(7, 'Alex', 10.25),
(8, 'Jane', 10.25),
(9, 'Alex', 20.55)
SELECT Seller, Amount, LAG(Amount,1) OVER (PARTITION BY Seller ORDER BY Seller) AS RunningTotal FROM Sales
Essentially in this example I would expect the following output
Seller|Amount|Running Total
Alex|10.00|10.00
Alex|1.25|20.25
Alex|20.55|40.90
Jane|10.25|10.25
Pete|10.25|10.25
Sarah|15.00|15.00
Tracy|10.25|10.25
Tracy|11.00|21.25
Tracy|10.25|31.50
Hope someone can help and thanks in advance. Dave
Solution
I am guessing you have an sql server, but it should alspo work on other rdms that support window functions
SELECT Seller , Amount , SUM(Amount) OVER (PARTITION BY Seller ORDER BY Seller ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal FROM Sales GO
Seller | Amount | RunningTotal :----- | ------: | -----------: Alex | 10.0000 | 10.0000 Alex | 10.2500 | 20.2500 Alex | 20.5500 | 40.8000 Jane | 10.2500 | 10.2500 Pete | 10.2500 | 10.2500 Sarah | 15.0000 | 15.0000 Tracy | 10.2500 | 10.2500 Tracy | 11.0000 | 21.2500 Tracy | 10.2500 | 31.5000
db<>fiddle here
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange