empTable EmpNo PNo Sal Red ----- --- ---- --- 1000 11 1200 430 1000 12 100 55 1000 13 120 7 1000 14 430 8 1000 15 300 40 1000 43 200 20 1000 56 100 232 1010 11 1000 300 1010 12 410 545 1010 13 300 54 1010 14 110 700 1010 19 200 500 EmpNoごとで、 PNoの少なくとも1つが19,24,45,67,89,99の場合は、PNo=19の行のRedを求める。 そうでない場合は最大のSalを求める。 出力結果 EmpNo Sal ----- ---- 1000 1200 1010 500
create table empTable(EmpNo,PNo,Sal,Red) as select 1000,11,1200,430 from dual union all select 1000,12, 100, 55 from dual union all select 1000,13, 120, 7 from dual union all select 1000,14, 430, 8 from dual union all select 1000,15, 300, 40 from dual union all select 1000,43, 200, 20 from dual union all select 1000,56, 100,232 from dual union all select 1010,11,1000,300 from dual union all select 1010,12, 410,545 from dual union all select 1010,13, 300, 54 from dual union all select 1010,14, 110,700 from dual union all select 1010,19, 200,500 from dual;
select EmpNo, case max(case when PNo in(19,24,45,67,89,99) then 1 else 0 end) when 1 then max(decode(PNo,19,Red)) else max(Sal) end as Sal from empTable group by EmpNo order by EmpNo;
単純case式と検索case式とdecode関数 を使い分けています。 結構読みやすい使い分けだと思います。