トップページに戻る    次のSQLパズルへ    前のSQLパズルへ

3-3 case式と集合関数

SQLパズル

テーブル
Val
---
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20

最小の3の倍数と、最大の3の倍数と、
最小の5の倍数と、最大の5の倍数を出力する

出力結果
最小の3の倍数   最大の3の倍数   最小の5の倍数  最大の5の倍数
-------------  -------------  -------------  -------------
           12             18             10             20


SQL

select
min(case when mod(Val,3) = 0 then Val end) as "最小の3の倍数",
max(case when mod(Val,3) = 0 then Val end) as "最大の3の倍数",
min(case when mod(Val,5) = 0 then Val end) as "最小の5の倍数",
max(case when mod(Val,5) = 0 then Val end) as "最大の5の倍数"
from (select 10 as Val
union select 11
union select 12
union select 13
union select 14
union select 15
union select 16
union select 17
union select 18
union select 19
union select 20) dummy;


解説

case式と、集合関数を組み合わせると、
条件を満たす集合の中で、最大値や最小値を取得できます