2011-12-07 8 views
1

こんにちは私はOracle SQLに小さな質問があります。 私はテーブルAuto_PartsありますSQLはグループ化データの例を追加します

Category,Manufacturer_id,Part_name 
Tires,Michelin, Pilot Pro 
Tires,Michelin, Power One 
Tires,Bridgestone, Potenza 
Tires,Bridgestone, Turanza 
Tires,Bridgestone, Blizzak 

クエリ:

select Category,Manufacturer_id,count(*) cnt,example_1,example_2,example_3 
    from auto_parts 
group by Category,Manufacturer_id 

結果:

Category,Manufacturer_id,cnt ,example_1,example_2,example_3 
Tires ,Michelin  ,1000 ,Pilot Pro,Power One,Power Two 
Tires ,Bridgestone ,200 ,Potenza ,Turanza ,Blizzak 

の質問:どのように私は上記の表から3つの任意の値を取得し、3としてそれらを提示することができますが私のクエリの列(上記のサンプル出力はexample_1,2,3です)

答えて

2

これはトリックを行う必要があります。もちろん、あなたがこの偉大な作業をされていただきありがとうございますブロックと、私はちょうど「...カテゴリーを選択して、」あなたのクエリがで開始するので、あなたのデータを模倣することを使用

with auto_parts as 
(
select 'Tires' as Category,'Michelin' as Manufacturer_id, 'Pilot Pro' as part_name from dual union all 
select 'Tires' as Category,'Michelin' as Manufacturer_id, 'Power One' as part_name from dual union all 
select 'Tires' as Category,'Bridgestone' as Manufacturer_id, 'Potenza' as part_name from dual union all 
select 'Tires' as Category,'Bridgestone' as Manufacturer_id, 'Turanza' as part_name from dual union all 
select 'Tires' as Category,'Bridgestone' as Manufacturer_id, 'Blizzak' as part_name from dual 
) 
select 
    Category 
    Manufacturer_id, 
    count(*) cnt , 
    max(case when rn = 1 then part_name end) example_1, 
    max(case when rn = 2 then part_name end) example_2, 
    max(case when rn = 3 then part_name end) example_3 
from (
    select category, manufacturer_id, part_name, row_number() over (partition by category, manufacturer_id order by dbms_random.value) rn 
    from auto_parts 
) 
group by Category,Manufacturer_id; 
+0

を必要としません。 – user1086362

関連する問題