mysql分组查询前n条数据

建表:

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)

结果图:

技术分享

技术分享

 原理剖析:

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。