mysql 取每组前几条记录

一、对分组的记录取前N条记录:例如:取每组的前3条最大的记录

1.用子查询:
SELECT * FROM tableName a  WHERE 3>
(SELECT COUNT(*) FROM  tableName b WHERE b.id=a.id AND b.cnt>a. cnt)
ORDER BY a.id,a.account DESC
 
2.用exists半连接:
SELECT * FROM  tableName a  WHERE EXISTS
(SELECT COUNT(*) FROM  tableName b WHERE b.id=a.id AND a.account<b. cnt HAVING COUNT(*)<3)
ORDER BY a.id,a. cntDESC
 
二、同理可以取组内最小的N条记录: 例如:取每组的前3条最小的记录
1、子查询
SELECT * FROM  tableName  a  WHERE 3>
(SELECT COUNT(*) FROM  tableName  b WHERE b.id=a.id AND b. cnt<a. cnt)
ORDER BY a.id,a. cnt DESC
 
2、用exists:
SELECT * FROM  tableName  a  WHERE EXISTS
(SELECT COUNT(*) FROM  tableName  b WHERE b.id=a.id AND a. cnt>b. cnt HAVING COUNT(*)<3)
ORDER BY a.id,a. cnt DESC
 
 

你可能感兴趣的:(mysql,分组,最大值,最小值,每组三条记录)