MySql分組取前幾名的寫法

2021-10-17 01:35:26 字數 943 閱讀 7830

1、準備測試資料

create table tb(name varchar(10),val int,memo varchar(20)); 

insert into tb values('a', 2, 'a2(a的第二個值)')

insert into tb values('a', 1, 'a1--a的第乙個值')

insert into tb values('a', 3, 'a3:a的第三個值')

insert into tb values('b', 1, 'b1--b的第乙個值')

insert into tb values('b', 3, 'b3:b的第三個值')

按照 name分組,取出每組前兩名(這個可以自定義)寫法為:

select 

tba.name,

tba.val

from tb tba

where 2 > ( select count(*) from tb tbb where tbb.name = tba.name and tbb.val > tba.val )

order by

tba.name,

tba.val desc

結果為:

mysql 取分組資料的前幾名(1)

目前有需求需要取分組資料的前幾名,有如下的解決方案來實現 具體資料庫如下 sql寫法 select from student grade as a where select coun from student grade as b where b.subid a.subid and b.grade ...

取前幾名的例子

給個例子參考 查詢每門課程的前2名成績 create table studentgrade stuid char 4 學號 subid int,課程號 grade int,成績 primary key stuid,subid go 表中資料如下 insert into studentgrade st...

MySQL 分組後取前幾條

利用group concat和substring index實現,能很好的利用索引,適合大資料。select from yourtable where id in select substring index group concat id order by column 2 desc 1 id f...