既存のコード体系を新しい体系に変換して集計する
以下のようなテーブルがある。
地方でグルーピングし、集計を行う。
select case pref_name
when "徳島" then "四国"
when "香川" then "四国"
when "愛媛" then "四国"
when "高知" then "四国"
when "福岡" then "九州"
when "佐賀" then "九州"
when "長崎" then "九州"
else "その他"
end as district,
sum(population)
from PopTbl
-- ここで別名であるdistrictを指定する書き方は標準SQL違反らしい
-- OrcleやSQLServerではエラーとなる。
group by district
人口階級ごとに都道府県を分類する。
select case
when population < 100 then "01"
when population < 200 then "02"
when population < 300 then "03"
when population >= 300 then "04"
else null
end as pop_class,
count(*) as cnt
from PopTbl
group by pop_class
order by pop_class;
異なる条件の集計を1つのSQLで行う
性別ごとに集計を取る場合、通常は男性の集計を行うSQL、女性の集計を行うSQLと2回のSQLを実行する。
-- 男性の集計
select pref_name,
sum(population)
from PopTbl
where sex = "1"
group by pref_name;
-- 女性の集計
select pref_name,
sum(population)
from PopTbl
where sex = "1"
group by pref_name;
case式を使用することで、1回のSQLで結果を取得できる。
select pref_name,
sum(case when sex = "1" then population else 0 end) as cnt_m,
sum(case when sex = "2" then population else 0 end) as cnt_f
from PopTbl
group by pref_name;
条件を分岐させたUPDATE
以下の条件で値を更新する。
1.給料が30万以上の場合、10%減給
2.給料が25万以上28万以下の場合、20%昇給
update Salaries
set salary =
case
when salary >= 300000 then salary * 0.9
when salary >= 250000 and salary <= 280000 then salary * 1.2
else salary
end;
クロス表を作成する
select course_name,
case
when course_id in (select course_id from OpenCourses where month = "200706") then "◯" else "×"
end as "6月",
case
when course_id in (select course_id from OpenCourses where month = "200707") then "◯" else "×"
end as "7月",
case
when course_id in (select course_id from OpenCourses where month = "200708") then "◯" else "×"
end as "8月"
from CourseMaster;