《SQL進階教程》抄書筆記01-case表達式
阿新 • • 發佈:2019-01-12
哈爾濱 函數 ast mas alt 情況 tmp lse rac
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 poptbl2 group 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 elsesalary 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;
很神奇的腦洞。
《SQL進階教程》抄書筆記01-case表達式