建表:

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)

结果图:

mysql分组查询前n条数据

mysql分组查询前n条数据

 原理剖析:

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-02-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-05
  • 2021-10-14
  • 2022-01-01
  • 2022-12-23
  • 2021-11-24
  • 2022-01-01
相关资源
相似解决方案