Hi everyone,
I have a table Sales
and I need to calculate the running total SaleAmount
for each day. How can I write this query?
Home / DeveloperSection / Forums / SQL Query to Calculate Running Total in SQL Server
Hi everyone,
I have a table Sales
and I need to calculate the running total SaleAmount
for each day. How can I write this query?
Ravi Vishwakarma
16-Jul-2024To calculate a running total in SQL Server, you can use the
SUM
function along with theOVER
clause.Here’s an example query that calculates a running total of the
Amount
column in a table calledTransactions
:Example Table Schema
Assume you have a table named
Transactions
with the following schema:Insert data to Table
Sample Query
Here's how you can calculate the running total:
Explanation:
SELECT TransactionID, TransactionDate, Amount
: Selects the columns to display.SUM(Amount) OVER (ORDER BY TransactionDate) AS RunningTotal
:SUM(Amount)
calculates the sum of theAmount
column.OVER (ORDER BY TransactionDate)
specifies the order in which the rows are processed. It calculates the running total for each row in the order ofTransactionDate
.AS RunningTotal
names the calculated column asRunningTotal
.FROM Transactions
: Specifies the table to query.ORDER BY TransactionDate
: Orders the final result set byTransactionDate
.This query will produce a result set with each row showing the
TransactionID
,TransactionDate
,Amount
, and theRunningTotal
up to that row, ordered byTransactionDate
.Or
This query will produce a result set with each row showing the
TransactionDate
, and theRunningTotal
up to that row.Read more
Describe Common Table Expressions (CTEs) in SQL server.
How to Join Multiple Tables and Retrieve Specific Columns in SQL Server?
Implement row-level security in SQL Server to restrict access to data to users.