SQL-CASE表达式
关于CASE表达式:
CASE WHEN <求值表达式> THEN <表达式> WHEN <求值表达式> THEN <表达式> WHEN <求值表达式> THEN <表达式> . . . ELSE <表达式> END
高级应用提示:
新手用WHERE、HAVING子句进行条件分支,高手用SELECT子句进行条件分支 ——《SQL进阶教程》作者:Mick
SQL-CASE表达式练习:
选出x,y中最大值:
--题目代码-- INSERT INTO `greatests` VALUES('A',1,2,3); INSERT INTO `greatests` VALUES('B',5,5,2); INSERT INTO `greatests` VALUES('C',4,7,1); INSERT INTO `greatests` VALUES('D',3,3,8); --x,y中最大值-- SELECT `key`, CASE WHEN `x` > `y` THEN `x` ELSE `y` END AS greatest FROM `greatests`
选出x,y,z中最大值:
--x,y,z中最大值-- SELECT `key`, CASE WHEN `z` > (CASE WHEN `x` > `y` THEN `x` ELSE `y` END) THEN `z` ELSE (CASE WHEN`x` > `y` THEN `x` ELSE `y` END) END AS greatest FROM `greatests`
最终输出:
将输出结果按B-A-D-C排序:
-- x,y,z中最大值 -- -- 并将输出结果按B-A-D-C排序 -- SELECT `key`, CASE WHEN `z` > ( CASE WHEN `x` > `y` THEN `x` ELSE `y` END ) THEN `z` ELSE ( CASE WHEN `x` > `y` THEN `x` ELSE `y` END ) END AS greatest FROM `greatests` ORDER BY CASE `key` WHEN 'A' THEN 'B' WHEN 'B' THEN 'A' WHEN 'C' THEN 'D' WHEN 'D' THEN 'C' END
运用CASE表达式转置表
题目:
/* 用一条SQL语句进行不同条件的统计 */ CREATE TABLE PopTbl2 (pref_name VARCHAR(32), sex CHAR(1) NOT NULL, population INTEGER NOT NULL, PRIMARY KEY(pref_name, sex)); INSERT INTO PopTbl2 VALUES('德岛', '1', 60 ); INSERT INTO PopTbl2 VALUES('德岛', '2', 40 ); INSERT INTO PopTbl2 VALUES('香川', '1', 100); INSERT INTO PopTbl2 VALUES('香川', '2', 100); INSERT INTO PopTbl2 VALUES('爱媛', '1', 100); INSERT INTO PopTbl2 VALUES('爱媛', '2', 50 ); INSERT INTO PopTbl2 VALUES('高知', '1', 100); INSERT INTO PopTbl2 VALUES('高知', '2', 100); INSERT INTO PopTbl2 VALUES('福冈', '1', 100); INSERT INTO PopTbl2 VALUES('福冈', '2', 200); INSERT INTO PopTbl2 VALUES('佐贺', '1', 20 ); INSERT INTO PopTbl2 VALUES('佐贺', '2', 80 ); INSERT INTO PopTbl2 VALUES('长崎', '1', 125); INSERT INTO PopTbl2 VALUES('长崎', '2', 125); INSERT INTO PopTbl2 VALUES('东京', '1', 250); INSERT INTO PopTbl2 VALUES('东京', '2', 150);
期望输出:
题解:
1 SELECT 2 CASE 3 sex 4 WHEN 1 THEN 5 '男' ELSE '女' 6 END AS 性别, 7 SUM( population ) AS total, 8 SUM( CASE WHEN pref_name = '德岛' THEN population ELSE 0 END ) AS '德岛' , 9 SUM( CASE WHEN pref_name = '香川' THEN population ELSE 0 END ) AS '香川', 10 SUM( CASE WHEN pref_name = '爱媛' THEN population ELSE 0 END ) AS '爱媛', 11 SUM( CASE WHEN pref_name = '高知' THEN population ELSE 0 END ) AS '高知', 12 SUM( CASE WHEN pref_name IN ( '德岛', '香川', '爱媛', '高知' ) THEN population ELSE 0 END ) AS '四国' 13 FROM 14 PopTbl2 15 GROUP BY 16 CASE 17 sex 18 WHEN 1 THEN 19 '男' ELSE '女' 20 END;
分析:
本题用到了CASE的两个知识点
1.CASE写在SUM中,实现转置;
2.CASE写在GROUP BY中,将‘1’和‘2’替换成‘男’‘女’后再分组。