Possible Duplicate:
How do I calculate a running total in SQL without using a cursor?
It's a little difficult to explain, so I'll show what I want with an example:
Lets say we have the following table named MonthProfit
:
[MonthId][Profit]
1, 10 -- January
2, 20 -- February
3, 30
4, 40
5, 50
6, 60
7, 70
8, 80
9, 90
10, 100
11, 110
12, 120 -- December
Column profit
represents the profit for that month.
However, if we have 10 profit in January, and 20 in February, in February we have a total profit of 30.
so I'd like to create a view that shows the following:
[MonthId][Profit][ProfitTotal]
1, 10, 10 -- January
2, 20, 30 -- February
3, 30, 60
4, 40, 100
5, 50, 150
6, 60, 210
7, 70, 280
8, 80, 360
9, 90, 450
10, 100, 550
11, 110, 660
12, 120, 780 -- December
What I did now to solve it, is a view like this:
SELECT [MonthId]
,[Profit]
, (SELECT SUM([Profit])
FROM MonthProfit
WHERE [MonthId] <= outer.[MonthId]) as ProfitTotal
FROM MonthProfit as outer
However, I assume this is pretty slow because it has to recount everything all the time, and it does not seem very elegant to me. Is there a "good" way to do this?