《SQL進階教程》抄書筆記01-case表示式
阿新 • • 發佈:2019-01-12
1.1 區域人口總數統計
轉換成
-- 注意group by後跟的條件
select case pref_name when '北京' then '北方' when '哈爾濱' then '北方' when '廣州' then '南方' when '深圳' then '南方' else '其他' end as district, sum(population) as total from poptbl group by case pref_name when '北京' then'北方' when '哈爾濱' then '北方' when '廣州' then '南方' when '深圳' then '南方' else '其他' end
1.2 行統計轉為列統計
轉換為
select pref_name, sum(case when sex=1 then population else 0 end) as male, -- 注意使用了sum函式 sum(case when sex=2 then population else 0 end) as female from poptbl2group by pref_name
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; -- 注意一定要寫else,否則不在上述條件裡面的工資會被置為NULL
select course_name, case when exists ( select * from opencourses OC where CM.course_id = OC.course_id and OC.month = '200706' ) then 'o' else 'x' end as '6月', case when exists ( select * from opencourses OC where CM.course_id = OC.course_id and OC.month = '200707' ) then 'o' else 'x' end as '7月', case when exists ( select * from opencourses OC where CM.course_id = OC.course_id and OC.month = '200708' ) then 'o' else 'x' end as '8月' from coursemaster CM
-- 先查出只加入了一個社團的學生的社團ID select std_id, max(club_id) from studentclub group by std_id having count(*) = 1 -- 再查出有主社團標誌的社團ID select std_id, club_id from studentclub where main_club_flg = 'Y'
解法2:使用case表示式,一個sql即可完成
-- select後跟的欄位,要麼是分組欄位,要麼被包含到聚合函式中 -- 聚合函式計算某個欄位時自動忽略null行 select std_id, case when count(*)=1 then max(club_id) else max(case when main_club_flg='Y' then club_id else null end) end as main_club from studentclub group by std_id
select `key`, greatest(x,y,z) as max from greatests
select `key`, case when x < y then (case when y < z then z else y end) else (case when x < z then z else x end) end as max from greatests
解法3:行列轉換後使用max函式
SELECT `key`, MAX(col) AS greatest FROM ( SELECT `key`, x AS col FROM Greatests UNION ALL SELECT `key`, y AS col FROM Greatests UNION ALL SELECT `key`, z AS col FROM Greatests )TMP GROUP BY `key`;
1.7 自定義order by
select `key` from greatests order by `key`
得到結果如下
select `key` from greatests order by case when `key`='B' then 1 when `key`='A' then 2 when `key`='D' then 3 when `key`='C' then 4 else null end;
很神奇的腦洞。