LoginSignup
0
0

More than 3 years have passed since last update.

MySQLでcase式を扱う(その2)

Posted at

既存のコード体系を新しい体系に変換して集計する

以下のようなテーブルがある。

スクリーンショット 2020-09-25 20.34.47.png

地方でグルーピングし、集計を行う。

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

スクリーンショット 2020-09-25 20.41.37.png

人口階級ごとに都道府県を分類する。

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;

スクリーンショット 2020-09-25 20.52.10.png

異なる条件の集計を1つのSQLで行う

以下のテーブルがある。
スクリーンショット 2020-09-26 10.33.00.png

性別ごとに集計を取る場合、通常は男性の集計を行う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;

スクリーンショット 2020-09-26 10.39.10.png

条件を分岐させたUPDATE

以下のテーブルがある。
スクリーンショット 2020-09-26 10.52.55.png

以下の条件で値を更新する。
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;

スクリーンショット 2020-09-26 11.10.18.png

クロス表を作成する

以下のテーブルがある。
スクリーンショット 2020-09-26 11.42.26.png

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;

スクリーンショット 2020-09-26 11.43.26.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0