SELECT
SUM(CASE WHEN sex=0 THEN 1 ELSE 0 END) AS 女生人数,
SUM(CASE WHEN sex=1 THEN 1 ELSE 0 END) AS 男生人数,
SUM(CASE WHEN score>=60 AND sex=0 THEN 1 ELSE 0 END) 男生及格人数,
SUM(CASE WHEN score>=60 AND sex=1 THEN 1 ELSE 0 END) 女生及格人数
FROM score;
结果
:
再看第2个场景
将上面的score表转换为下面形式:
SQL:
SELECT
name,
MAX(CASE course WHEN '语文' THEN score ELSE 0 END) AS '语文',
max(CASE course WHEN '数学' THEN score ELSE 0 END) AS '数学',
max(CASE course WHEN '英语' THEN score ELSE 0 END) AS '英语',
AVG(score) AS '平均成绩'
FROM score GROUP BY name;