SQL进阶教程学习笔记1.1
SELECT CASE pref_name
WHEN '辽宁' THEN '东北'
WHEN '福建' THEN '东南'
ELSE '其他' END AS district,
SUM(population)
FROM PopTb1
GROUP BY CASE pref_name
WHEN '辽宁' THEN '东北'
WHEN '福建' THEN '东南'
ELSE '其他' AS END;
SELECT CASE pref_name
WHEN '辽宁' THEN '东北'
WHEN '福建' THEN '东南'
ELSE '其他' END AS district,
SUM(population)
FROM PopTb1
GROUP BY district;
注意事项 END\ELSE
SELECT pref_name,
--男性
SUM( CASE WHEN sex = "男" THEN population ELSE 0 END) AS cnt_m,
--女性
SUM( CASE WHEN sex = "女" THEN population ELSE 0 END) AS cnt_f
FROM PopTbl2
GROUP BY pref_name;
分别统计:将行结构转换成列结构。
SELECT 语句 条件分支
蕴含式逻辑 VS 逻辑“与”
--CASE + UPDATE
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;
--最后一行表示不符合以上条件的返回初始值
--use IN
SELECT course_name,
CASE WHEN course_id IN
(SELECT course_id FROM OpenCourses
WHERE month = 200706) THEN 'O'
ELSE 'X' END AS "June",
CASE WHEN course_id IN
(SELECT course_id FROM OpenCourses
WHERE month = 200707) THEN 'O'
ELSE 'X' END AS "July"
FROM CourseMaster;
--use EXISTS better than IN, BECAUSE 性能更好
SELECT CM.course_name,
CASE WHEN EXISTS
(SELECT course_id FROM OpenCourses AS OC
WHERE month = 200706
AND OC.course_id = CM.course_id) THEN 'O'
ELSE 'X' END AS "June",
CASE WHEN EXISTS
(SELECT course_id FROM OpenCourses AS OC
WHERE month = 200707
AND OC.course_id = CM.course_id) THEN 'O'
ELSE 'X' END AS "July"
FROM CourseMaster AS CM;
--获取仅参加一个club的club_id、以及参加多个的main_club_id
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;
CASE是一个表达式,而不是语句,可作为值进行返回。
--两两比大小
SELECT key,
CASE WHEN x > y THEN x
ELSE y END AS greatest
FROM Greatests;
--三个排序
SELECT key,
CASE WHEN CASE WHEN x < y THEN y ELSE x END < z
THEN z
ELSE CASE WHEN x < y THEN y ELSE x END
END AS greatest
FROM Greatests;
CASE WHEN CASE WHEN x < y THEN y ELSE x END < z
max{x, y} = CASE WHEN x < y THEN y ELSE x END
/* 转换行列——在表头里加入汇总和再揭(p.287) */
SELECT sex,
SUM(population) AS total,
SUM(CASE WHEN pref_name = '德岛' THEN population ELSE 0 END) AS col_1,
SUM(CASE WHEN pref_name = '香川' THEN population ELSE 0 END) AS col_2,
SUM(CASE WHEN pref_name = '爱媛' THEN population ELSE 0 END) AS col_3,
SUM(CASE WHEN pref_name = '高知' THEN population ELSE 0 END) AS col_4,
SUM(CASE WHEN pref_name IN ('德岛', '香川', '爱媛', '高知')
THEN population ELSE 0 END) AS zaijie
FROM PopTbl2
GROUP BY sex;
/* 用ORDER BY生成“排序”列 */
SELECT key
FROM Greatests
ORDER BY CASE key
WHEN 'B' THEN 1
WHEN 'A' THEN 2
WHEN 'D' THEN 3
WHEN 'C' THEN 4
ELSE NULL END;
/* 把“排序”列也包括在结果中(p.288) */
SELECT key,
CASE key
WHEN 'B' THEN 1
WHEN 'A' THEN 2
WHEN 'D' THEN 3
WHEN 'C' THEN 4
ELSE NULL END AS sort_col
FROM Greatests
ORDER BY sort_col;