Skip to content

Instantly share code, notes, and snippets.

@orette
Created March 23, 2015 20:34
Show Gist options
  • Save orette/d2ff6a95ae3e389c7c49 to your computer and use it in GitHub Desktop.
Save orette/d2ff6a95ae3e389c7c49 to your computer and use it in GitHub Desktop.
Calculating simple running totals in SQL Server
--Source : http://www.codeproject.com/Articles/300785/Calculating-simple-running-totals-in-SQL-Server
--First we need a table for the data. To keep things simple, let's create a table with just an auto incremented id and a value field.
CREATE TABLE RunTotalTestData (
id int not null identity(1,1) primary key,
value int not null
);
--And populate it with some data:
INSERT INTO RunTotalTestData (value) VALUES (1);
INSERT INTO RunTotalTestData (value) VALUES (2);
INSERT INTO RunTotalTestData (value) VALUES (4);
INSERT INTO RunTotalTestData (value) VALUES (7);
INSERT INTO RunTotalTestData (value) VALUES (9);
INSERT INTO RunTotalTestData (value) VALUES (12);
INSERT INTO RunTotalTestData (value) VALUES (13);
INSERT INTO RunTotalTestData (value) VALUES (16);
INSERT INTO RunTotalTestData (value) VALUES (22);
INSERT INTO RunTotalTestData (value) VALUES (42);
INSERT INTO RunTotalTestData (value) VALUES (57);
INSERT INTO RunTotalTestData (value) VALUES (58);
INSERT INTO RunTotalTestData (value) VALUES (59);
INSERT INTO RunTotalTestData (value) VALUES (60);
--The scenario is to fetch a running total when the data is ordered ascending by the id field.
--Correlated scalar query
--One very traditional way is to use a correlated scalar query to fetch the running total so far. The query could look like:
SELECT a.id, a.value, (SELECT SUM(b.value)
FROM RunTotalTestData b
WHERE b.id <= a.id)
FROM RunTotalTestData a
ORDER BY a.id;
--Source : http://blog.sqlauthority.com/2014/10/04/sql-server-how-to-find-running-total-in-sql-server/
-- Running Total for SQL Server 2012 and Later Version
SELECT ID, Value,
SUM(Value) OVER(ORDER BY ID ROWS UNBOUNDED PRECEDING) AS RunningTotal
FROM RunTotalTestData
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment