mysql 取每组前几条记录
程序员文章站
2022-05-17 13:11:48
...
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
上一篇: 去除文本文件分组后的重复行