SQL题思考模式
- select 查询结果
- from 从哪张表中查找数据
- where 查询条件
- group by 分组
- having 对分组结果指定条件
- order by 对查询结果排序
- limit 取多少数据
TopN问题
工作中会经常遇到这样的业务问题:
如何找到每个类别下用户最喜欢的产品是哪个?
如果找到每个类别下用户点击最多的5个商品是什么?
这类问题其实就是常见的:分组取每组最大值、最小值,每组最大的N条(top N)记录。
方法:利用子查询
合并查询结果: union all 合并两个查询结果
(select * from score where 课程号 = '0001' order by 成绩 desc limit 2)
union all
(select * from score where 课程号 = '0002' order by 成绩 desc limit 2)
union all
(select * from score where 课程号 = '0003' order by 成绩 desc limit 2);
条件函数(case when)
select 课程号,
sum(case when 成绩›=60 then 1
else 0
end) as 及格人数,
sum(case when 成绩 ‹ 60 then 1
else 0
end