建表:
CREATE TABLE hard(
id INT,
aa varchar(50) ,
bb INT,
PRIMARY key(id)
)
insert into hard values(1,'a',9)
insert into hard values(2,'a',7)
insert into hard values(3,'a',8)
insert into hard values(4,'a',6)
insert into hard values(5,'b',2)
insert into hard values(6,'b',3)
insert into hard values(7,'b',4)
insert into hard values(8,'c',1)
insert into hard values(9,'c',8)
insert into hard values(10,'c',2)
查询该表中,每组的最大两个数:
select a.* from hard a where (select count(*) from hard where aa = a.aa and bb > a.bb ) < 2 order by a.aa,a.bb desc
此处 2 即为n
(查询单表不分组的前n条最大数据: select DISTINCT bb from hard order by bb desc limit 2)
结果图:
原理剖析: