SQL Server 2005 で while ループを使用せずにテーブル データを更新する
私はこの質問をし、詳細は....
SQLでは、以下のようなテーブルデータがあります
id type amount
1 type1 2000
2 type1 1000
3 type2 500
4 type3 3000
5 type1 2000
6 type2 500
7 type3 5000
8 type1 1000
そして、以下のようなselectステートメントでデータを取得したい
id type amount current
1 type1 2000 2000
2 type1 1000 1000
3 type2 500 500
4 type3 3000 3000
5 type1 2000 3000
6 type2 -500 0
7 type3 5000 2000
8 type1 -1000 4000
など、つまり、各タイプには金額タイプに基づいた現在の合計金額が必要であり、実行に時間がかかるため、while ループを使用する必要はありません。
for eg:
in type 1
ID Amount current
1 2000-add 2000
2 1000-sub 1000
3 2000-add 3000
4 1000-add 4000
答えは、
SELECT id,
type,
amount,
(SELECT sum(amount)
FROM mytable t1
WHERE t1.type = t2.type
AND t1.id <= t2.id) currenttotal
FROM mytable t2
ここでの問題は、サンプルテーブルに次のようなデータの8000(増加する)レコードがあると仮定することです
id type amount
1 type1 2000
2 type1 1000
3 type2 500
4 type3 3000
5 type1 2000
6 type2 500
7 type3 5000
8 type1 1000
00:00:02
上記の質問の回答(2つの回答があり、両方の実行時間が同じ)に基づいて作成したselectステートメントを実行するのに時間がかかります。この実行時間を短縮するにはどうすればよいですか?