トップページに戻る
次のSQLパズルへ
前のSQLパズルへ
4-16 重複排除とソート
SQLパズル
CodeTable
Code1 Code2 Code3 SortKey
----- ----- ----- -------
AAAAA BBBBB CCCCC 2
AAAAA BBBBB CCCCC 15
DDDDD BBBBB CCCCC 22
DDDDD BBBBB CCCCC 22
DDDDD BBBBB CCCCC 23
EEEEE FFFFF GGGGG 1
EEEEE FFFFF GGGGG 35
HHHHH IIIII JJJJJ 7
HHHHH IIIII JJJJJ 47
Code1,Code2,Code3ごとで重複を排除して出力する。
出力順は、Code1,Code2,Code3ごとの最小のSortKeyの昇順とする。
出力結果
CODE1 CODE2 CODE3
----- ----- -----
EEEEE FFFFF GGGGG
AAAAA BBBBB CCCCC
HHHHH IIIII JJJJJ
DDDDD BBBBB CCCCC
データ作成スクリプト
create table CodeTable(Code1,Code2,Code3,SortKey) as
select 'AAAAA','BBBBB','CCCCC', 2 from dual union all
select 'AAAAA','BBBBB','CCCCC',15 from dual union all
select 'DDDDD','BBBBB','CCCCC',22 from dual union all
select 'DDDDD','BBBBB','CCCCC',22 from dual union all
select 'DDDDD','BBBBB','CCCCC',23 from dual union all
select 'EEEEE','FFFFF','GGGGG', 1 from dual union all
select 'EEEEE','FFFFF','GGGGG',35 from dual union all
select 'HHHHH','IIIII','JJJJJ', 7 from dual union all
select 'HHHHH','IIIII','JJJJJ',47 from dual;
SQL
■■■group byで重複を排除する方法■■■
select Code1,Code2,Code3
from CodeTable
group by Code1,Code2,Code3
order by min(SortKey);
■■■分析関数を使う方法■■■
select Code1,Code2,Code3
from (select Code1,Code2,Code3,SortKey,
Row_Number() over(partition by Code1,Code2,Code3 order by SortKey) as Rn
from CodeTable)
where Rn = 1
order by SortKey;
解説