时间:2021-07-01 10:21:17 帮助过:111人阅读
取GID每组 COL2最大的3条记录:
SELECT a.id,a.gid,a.col1,a.col2 FROM t2 a
WHERE 3>=(
SELECT COUNT(*) FROM t2 b
WHERE a.gid=b.gid AND a.col2<=b.col2)
ORDER BY a.gid,a.col2 desc
或
SELECT a.id,a.gid,a.col1,a.col2 FROM t2 a
LEFT JOIN t2 b
ON a.gid=b.gid AND a.col2<=b.col2
GROUP BY a.id,a.gid,a.col1,a.col2
HAVING COUNT(b.id)<=3
ORDER BY a.gid,a.col2 desc
MySQL 先按某字段分组,再取每组中前N条记录
标签:mysq from col desc gid sql sele esc 分组