目的:資料轉置
說明:原資料為正規後之資料格式,在輸出時需轉為橫向輸出 (如下圖)
語法:
select year, title, area_code, col_type, col_range,
MAX(case when `count_type` = 'total' then count else 0 end) as T,
MAX(case when `count_type` = 'male' then count else 0 end) as M,
MAX(case when `count_type` = 'female' then count else 0 end) as F
from date
where area_code = '0301'
group by col_range
利用case產生新的欄位,保留符合條件的數值並將其他設為0,配合MAX及Group by篩出最大值並合併資料。
如果沒有加MAX及Group by,那結果就會是下面這樣
全站熱搜