简体   繁体   中英

Select rows from mysql table with limit by group

I have the table

id    code    name
=====================
1     30100   John
2     30100   Andrew
3     30100   Sandy
4     29145   Mike
5     29145   Tony
6     29145   Laura
7     29145   Henry
8     00124   Michael
9     00124   Teddy
10    13405   Andy
11    09325   Patrick

I want to select only 2 names grouped by code and get this result.

id    code    name
=====================
1     30100   John
2     30100   Andrew
4     29145   Mike
5     29145   Tony
8     00124   Michael
9     00124   Teddy
10    13405   Andy
11    09325   Patrick

Can somebody help me to make such query/queries?

Thanks

SELECT id, code, name
FROM   TableName a
WHERE
(
   SELECT count(*) 
   FROM   TableName as f
   WHERE  f.code = a.code and a.id >= f.id
) <= 2
ORDER BY id, code, name 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM