Oracle 10g にはPIVOT
関数がないため、以下の集計を使用できますCASE
。
select
sum(case when type1 = 'T1' then total end) T1,
sum(case when type1 = 'T2' then total end) T2
from <yourquery goes here>
デモで SQL Fiddle を参照してください
または、これを次のようなクエリに直接実装することもできます。SUM()
集計を使用すると、ステートメント内のtype1
値に一致する各オカレンスがカウントされます。CASE
select
sum(case when type1 = 'T1' then 1 else 0 end) T1,
sum(case when type1 = 'T2' then 1 else 0 end) T2
from yourtable
列に変換する値の数が不明な場合は、次のような手順を使用する必要があります。
CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
as
sql_query varchar2(1000) := 'select ';
begin
for x in (select distinct type1 from yourtable order by 1)
loop
sql_query := sql_query ||
' , sum(case when type1 = '''||x.type1||''' then 1 else 0 end) as '||x.type1;
dbms_output.put_line(sql_query);
end loop;
sql_query := sql_query || ' from yourtable';
open p_cursor for sql_query;
end;
/
それを実行するには:
variable x refcursor
exec dynamic_pivot(:x)
print x