私は次の形式で結果セットを返したい:Oracle - 集計合計とピボット集計合計を戻しますか?
YEARMONTH Total ModelA ModelB ModelC
200101 0 0 0 0
200102 10 5 5 0
200103 8 2 2 4
合計がYEARMONTHでグループ化されたすべてのモデルタイプのための時間の和であり、個々のモデルの列は、モデルごとの時間の合計であるところタイプは年ごとに分類されます。私は、ネストされた選択で次のクエリを使用して、正しい結果を得ることができます。
select distinct yearmonth,
sum(a.hours) as Total,
(select sum(b.hours) from model_hours b
where model = 'ModelA' and a.yearmonth = b.yearmonth) as ModelA,
(select sum(b.hours) from model_hours b
where model = 'ModelB' and a.yearmonth = b.yearmonth) as ModelB,
(select sum(b.hours) from model_hours b
where model = 'ModelC' and a.yearmonth = b.yearmonth) as ModelC
from model_hours a
group by yearmonth
order by yearmonth
私は同じ結果を達成するために、Oracle 11でピボット機能を使用して試して興味があった、との合計を除くすべての結果を得ることができています次のクエリを使用して時間:私はグラムまた、すべてのモデルのための時間の合計を取得する方法を見つけ出すことができていない
YEARMONTH ModelA ModelB ModelC
200101 0 0 0
200102 5 5 0
200103 2 2 4
:この結果を返す
select * from (
select yearmonth, hours, model
from model_hours a
)
pivot
(
sum(hours)
for model in ('ModelA', 'ModelB', 'ModelC')
)
order by yearmonth
この結果セットには、年末までに集まった。出来ますか?もしそうなら、ネストされた選択よりも効率的になるでしょうか?この特定のテーブルには現在約200Kの行があります。