Oracle PIVOT 句でユーザー定義の集計関数を使用できません。
string_agg というユーザー定義の集計関数を作成しました。
などの簡単な文で使用できます...
select id, string_agg(value) from
(
select 'user1' as id, 'BMW' as value, 'CAR' as type from dual union
select 'user1' as id, 'Audi' as value, 'CAR' as type from dual union
select 'user2' as id, 'Honda' as value, 'CAR' as type from dual union
select 'user1' as id, 'Dell' as value, 'COMPUTER' as type from dual union
select 'user1' as id, 'Sony' as value, 'COMPUTER' as type from dual union
select 'user2' as id, 'HP' as value, 'COMPUTER' as type from dual
)
group by id, type
結果:
ID TYPE STRING_AGG(VALUE)
user1 CAR Audi,BMW
user1 COMPUTER Dell,Sony
user2 CAR Honda
user2 COMPUTER HP
ただし、ピボット句で同じ関数を使用しようとすると
select * from
(
select id, type, string_agg(value) as value from
(
select 'user1' as id, 'BMW' as value, 'CAR' as type from dual union
select 'user1' as id, 'Audi' as value, 'CAR' as type from dual union
select 'user2' as id, 'Honda' as value, 'CAR' as type from dual union
select 'user1' as id, 'Dell' as value, 'COMPUTER' as type from dual union
select 'user1' as id, 'Sony' as value, 'COMPUTER' as type from dual union
select 'user2' as id, 'HP' as value, 'COMPUTER' as type from dual
)
group by id, type
)
PIVOT (string_agg(value) FOR id IN ('user1' user1, 'user2' user2) );
次のエラーが表示されます...
ORA-56902: expect aggregate function inside pivot operation
期待される結果は...
TYPE USER1 USER2
COMPUTER Dell,Sony HP
CAR Audi,BMW Honda