トップページに戻る
次のSQLパズルへ
前のSQLパズルへ
3-29 grouping setsで総合計を取得
SQLパズル
groupingTable
ColA ColB
---- ----
1 1
1 1
1 1
1 1
1 1
1 2
1 2
1 2
2 1
2 1
2 1
2 2
2 3
2 3
ColAとColBの組み合わせごとのレコード数と、
全のレコ−ド数を、
以下の形式で出力する。
出力結果
ColA ColB RecordCount
---- ---- -----------
1 1 5
1 2 3
2 1 3
2 2 1
2 3 2
null null 14
データ作成スクリプト
create table groupingTable as
select 1 as ColA,1 as ColB from dual
union all select 1,1 from dual
union all select 1,1 from dual
union all select 1,1 from dual
union all select 1,1 from dual
union all select 1,2 from dual
union all select 1,2 from dual
union all select 1,2 from dual
union all select 2,1 from dual
union all select 2,1 from dual
union all select 2,1 from dual
union all select 2,2 from dual
union all select 2,3 from dual
union all select 2,3 from dual;
SQL
--■■■union allを使う方法■■■
select ColA,ColB,count(*) as RecordCount
from groupingTable
group by ColA,ColB
union all
select null,null,count(*) as RecordCount
from groupingTable
order by ColA,ColB;
--■■■grouping setsを使う方法■■■
select ColA,ColB,count(*) as RecordCount
from groupingTable
group by grouping sets((ColA,ColB),())
order by ColA,ColB;
解説