SELECT文でCASE句を使うシチュエーション
例えばあるカラムの値がいくつ以上いくつ以下の時にはグループ1、いくつ以上いくつ以下の時にはグループ2とする、といったグルーピングをしたい時に使います。投稿日付が1ヶ月以内だったら「NEW」をつけるといった処理をしたいときに、SQL側でNEWフラグの有無を判断した上でプログラム側へ結果を返せるので便利です。
SELECT文でCASE句を使う具体例
まずは今回のサンプル用にテーブルを作成しておきます。
create table users(
id int primary key auto_increment,
name text not null,
age int
);
insert into users(name,age) values('あいだ',20);
insert into users(name,age) values('いとう',40);
insert into users(name,age) values('うただ',25);
insert into users(name,age) values('えもと',32);
insert into users(name,age) values('おかだ',77);
こんな感じになります。
select * from users;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | あいだ | 20 |
| 2 | いとう | 40 |
| 3 | うただ | 25 |
| 4 | えもと | 32 |
| 5 | おかだ | 77 |
+----+-----------+------+
このusersテーブルで、20歳以上30歳未満を「young」、30歳以上60歳未満を「middle」、60歳以上を「senior」と判別したいとします。
その時に以下のようなCASEを用いたSELECT文が使えます。
select name,age,
case
when age>=20 and age<30 then 'young'
when age>=30 and age<60 then 'middle'
when age>=60 then 'senior'
else 'none'
end as age_class
from users;
以下のように書くこともできます。
select name,age,
case age
when age>=20 and age<30 then 'young'
when age>=30 and age<60 then 'middle'
when age>=60 then 'senior'
else 'none'
end age_class
from users;
+-----------+------+-----------+
| name | age | age_class |
+-----------+------+-----------+
| あいだ | 20 | young |
| いとう | 40 | middle |
| うただ | 25 | young |
| えもと | 32 | middle |
| おかだ | 77 | senior |
+-----------+------+-----------+
各グループの人数を取得したいときには以下のようにCASE文を使えます。
select
sum(case when age>=20 and age<30 then 1 else 0 end) young_count,
sum(case when age>=30 and age<60 then 1 else 0 end) middle_count,
sum(case when age>=60 then 1 else 0 end) senior_count
from users;
+-------------+--------------+--------------+
| young_count | middle_count | senior_count |
+-------------+--------------+--------------+
| 2 | 2 | 1 |
+-------------+--------------+--------------+
SELECT文でCASE句を使う構文
case文は様々な使い方があるので、あまり一般化した構文にするのは難しいので、基本的なcase句の箇所だけまとめておきます。
case
when 【条件1】 then 【値1】
when 【条件2】 then 【値2】
・・・・
end 【必要があれば値用の仮のカラム名】