使用DB
postgresql 12.2
やりたいこと
テーブルデータの縦持ちを横持ちにして集計する。
参考にしたのは、達人に学ぶSQL徹底指南書 第2版
サンプルデータとして、以下のような県ごとの男女比別人口があるテーブルを用いる。
sex = 1 は男で、2は女である。
pref_name | sex | population |
---|---|---|
徳島 | 1 | 60 |
徳島 | 2 | 40 |
香川 | 1 | 100 |
香川 | 2 | 100 |
愛媛 | 1 | 100 |
愛媛 | 2 | 50 |
高知 | 1 | 100 |
高知 | 2 | 100 |
福岡 | 1 | 100 |
福岡 | 2 | 200 |
佐賀 | 1 | 20 |
佐賀 | 2 | 80 |
長崎 | 1 | 125 |
長崎 | 2 | 125 |
東京 | 1 | 250 |
東京 | 2 | 150 |
欲しい結果
男女別の徳島、香川、愛媛、高知の人口と、四国、すべてについての人口を得たい。
以下のように縦横変換されてほしい。
性別|徳島|香川 |愛媛 |高知 |四国 |すべて|
--|--|---|---|---|---|---|
男 |60|100|100|100|360|855|
女 |40|100| 50|100|290|845|
SQL
select
case when sex = '1' then '男' else '女' end as 性別
,sum(case when pref_name = '徳島' then population else 0 end) as 徳島
,sum(case when pref_name = '香川' then population else 0 end) as 香川
,sum(case when pref_name = '愛媛' then population else 0 end) as 愛媛
,sum(case when pref_name = '高知' then population else 0 end) as 高知
,sum(
case when pref_name = '徳島' then population
when pref_name = '香川' then population
when pref_name = '愛媛' then population
when pref_name = '高知' then population
else 0 end) as 四国
,sum(population) as すべて
from
poptbl2
group by
sex
order by
sex
;
感想
SQLのCASE式は強力な機能だなと思った。