Skip to main content

Calculate Running Total with Correlated Subquery in SQL Server

In this post, we'll go over an example of calculating running total of each employee's daily sales using a correlated subquery.

You can use this DB Fiddle to follow along and calculate Running Total with Subquery.

Sample Data for Running Total Calculation

Let’s create some sample data to demonstrate how to calculate running total using correlated subquery.

We will create a EmployeeSales table which has a EmployeeID, SaleDate, and SaleAmountcolumns. SaleAmount stores each employee's daily sales amount.

Create EmployeeSales Table
CREATE TABLE EmployeeSales(
[EmployeeID] INT,
[SaleDate] DATE,
[SaleAmount] INT
)

INSERT INTO EmployeeSales VALUES
(1,'2022-06-01',10),
(1,'2022-06-02',20),
(1,'2022-06-03',30),
(2,'2022-06-01',10),
(2,'2022-06-02',10),
(2,'2022-06-03',10)
EmployeeIDSaleDateSaleAmount
12022-06-0110
12022-06-0220
12022-06-0330
22022-06-0110
22022-06-0210
22022-06-0310

Calculate Running Total with Subquery

It's common to come across SQL codes calculating a running total using a subquery.

For every row in the original query, a correlated subquery is executed to compute the running total of the EmployeeID up to the SaleDate.

Calculate Running Total with Subquery
SELECT *
,(
SELECT SUM(SQ.SaleAmount)
FROM EmployeeSales AS SQ
WHERE SQ.EmployeeID = ES.EmployeeID
AND SQ.SaleDate <= ES.SaleDate
) AS RunningTotal
FROM EmployeeSales AS ES
EmployeeIDSaleDateSaleAmountRunningTotal
12022-06-011010
12022-06-022030
12022-06-033060
22022-06-011010
22022-06-021020
22022-06-031030

The code is easy to understand, but the subquery forces the query to scan the table for every row that exists in the original table.

This approach is usually fine when dealing with a fairly small dataset. But it's not recommended if you're dealing with a larger dataset as you might run into performance issues.

Therefore, you should consider using Self Join to compute running total or utilizing Window Function to calculate running total.