可能性の重複:
How do I calculate a running total in SQL without using a cursor?以前のすべての値の合計を取得しますか? - これまでの合計?
それは説明するのは少し難しいので、私は、私は例を挙げて欲しいもの紹介:
は、我々は次の表を考えてみましょう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
列profit
はその月の利益を表します。
の総利益を持っている場合
しかし、私は次のように表示するビューを作成したいのですが私はそれを解決するために、今やった
[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
は、このような図である。
SELECT [MonthId]
,[Profit]
, (SELECT SUM([Profit])
FROM MonthProfit
WHERE [MonthId] <= outer.[MonthId]) as ProfitTotal
FROM MonthProfit as outer
しかし、私はそれがすべてのすべての時間を詳述しているので、これはかなり遅いですと仮定し、それはVEのようではありません私にエレガントになりました。これを行う「良い」方法はありますか?
http://stackoverflow.com/questions/814054/complicated-sql-query-for-a-running-total-column – JNK
ただ、 "トータルSQLの実行" を検索しますこれに多くのヒットを得るでしょう。 – JNK