Thursday, July 28, 2011

SQL Server Query to find the running total of Amount in a table


/*
Given a Table Account(Id,Amount) calculate the running total of Amounts

E.g.
Id Amount
1  10
2  20
3  30

Output should be
Id Running_Amount
1  10
2  30
3  60
*/

SELECT id as Id,(SELECT SUM(amount) FROM account a2 WHERE a2.id<=a1.id) as Running_Amount
FROM account a1
ORDER BY a1.id

No comments:

Post a Comment