招聘季让面试官颤抖吧之sql实现分组topN
之前分组topN 一直都是算子来做的,今天复习一下 sql 怎么直接实现分组topN
首先我们创建一张表
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`course` varchar(20) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
添加一些数据
insert into student (name,course,score)
values
('张三','语文',80),
('李四','语文',90),
('王五','语文',93),
('张三','数学',77),
('李四','数学',68),
('王五','数学',99),
('张三','英语',90),
('李四','英语',50),
('王五','英语',89);
这边要怎么实现分组topN 呢
可以让自己join 自己 ,只join 分数比自己高的。最后做where 条件的时候 让 count 值小于N 即可
如下 求每个学生 top2 的成绩 :
select a.id,a.name,a.course,a.score
from student a left join student b on a.name=b.name and a.score<b.score
group by a.name,a.course,a.score
having count(b.id)<2
order by a.name,a.score desc;
或者 这样的 子查询的方式:
select *
from student a
where 2>(select count(*) from student where name=a.name and score>a.score)