SQL Running Total Sample in SQL Server 2008
Calculating sql running total in SQL Server queries is a common task for most of t-sql developers.
In order to display running totals for a quantity or amount column, easiest method in SQL Server is using t-sql CTE (Common Table Expression) structures.
This t-sql tutorial includes a sample case showing SQL Server running total of ordered product quantity for specific products in SQL Server sample database Adventureworks.
For sql running total sample code in SQL Server, I will use SQL Server 2008 R2 sample database AdventureWorks2008R2.
I want to query SalesOrderHeader and SalesOrderDetail sql tables in order to list all orders for a specific range of products, and list order information with order quantity in addition to total number of items ordered till that time by sql running sum.
If you are used to SQL CTE (Common Table Expression) syntax which is new with SQL Server 2005, sql developers will realize that the CTE expression is selecting all data required for SQL Server running total except the value itself.
The sub-select TotalOrderedQty is reading the RunningTotalCTE expression for all previous order items in order to calculate running sum for that specific product.
with RunningTotalCTE as (
from Sales.SalesOrderDetail d
inner join Sales.SalesOrderHeader h on d.SalesOrderID = h.SalesOrderID
where ProductID between 771 and 775
TotalOrderedQty = (
from RunningTotalCTE c
where c.SalesOrderID <= RunningTotalCTE.SalesOrderID
and c.ProductID = RunningTotalCTE.ProductID
When you run the above transact-sql query on SQL Server 2008 R2 AdventureWorks database, you will get a similar output in the following screenshot.
Please note that the TotalOrderedQty column has values showing running total values on order quantity for the related productid.