- 2007-05-12
- pgsql
ミックさんの問題に挑戦してみました。 case文を使う方が先に思いついたけど。こんな感じかな。 ヒラをどこで弾くかが微妙なところですが。
方法はいくつかありますが、代表的なものとしては、HAVINGを使ってUNIONする非効率的なものと、CASE式を使った効率的なものがあります。それぞれどんなクエリになるか、考えてみてください。
create table roles (
person text,
role text
);
copy roles from stdin;
スミス 部長
スミス 役員
ジョーンズ 部長
ホワイト 役員
ブラウン ヒラ
\.
select person
, '兼務'
from roles
group by person
having count(*) > 1
union
select person
, min(role)
from roles
where role <> 'ヒラ'
group by person
having count(*) = 1;
select person
, case when count(*) > 1 then '兼務'
else min(role)
end
from roles
where role <> 'ヒラ'
group by person;
min()はmax()でも一緒です。