当前位置:Gxlcms > mysql > mysql中GROUPBY分组取前N条记录实现

mysql中GROUPBY分组取前N条记录实现

时间:2021-07-01 10:21:17 帮助过:24人阅读

GROUP BY之后如何取每组的前两位下面我来讲述mysql中GROUP BY分组取前N条记录实现方法。

代码如下

mysql> select * from t_subject;
| id | uid | subject |
| 1 | 1 | aa |
| 2 | 2 | bb |
| 3 | 3 | cc |
| 4 | 4 | dd |
| 5 | 2 | ee |
| 6 | 2 | rr |
| 7 | 3 | tt |
| 8 | 2 | yy |
| 9 | 3 | qq |
| 10 | 4 | oo |
| 11 | 3 | pp |
| 12 | 3 | kk |
| 13 | 1 | mm |
| 14 | 4 | nn |
| 15 | 1 | ss |
| 16 | 4 | vv |
| 17 | 1 | ff |

SELECT uid, group_concat(subject)
FROM (SELECT id, uid, subject
FROM (SELECT id, uid, subject,
(SELECT COUNT(*)
FROM t_subject
WHERE uid = t.uid
AND subject <= t.subject) RK
FROM t_subject t) t1
WHERE rk <= 3) t2
GROUP BY uid

| uid | group_concat(a.subject) |
| 1 | aa,ff,ss,mm |
| 2 | yy,rr,ee,bb |
| 3 | kk,pp,xx,qq,tt,cc |
| 4 | nn,dd,vv,oo |

----我想要的是如下效果的 该怎么写啊(就是取出分组后每组的前三条记录)---

代码如下
| uid | group_concat(a.subject) |
| 1 | aa,ff,mm |
| 2 | yy,rr,ee |
| 3 | kk,pp,xx |
| 4 | nn,dd,vv |

实例二

mysql中GROUP BY分组取前N条记录实现

mysql分组,取记录

GROUP BY之后如何取每组的前两位下面我来讲述mysql中GROUP BY分组取前N条记录实现方法。


这是测试表(也不知道怎么想的,当时表名直接敲了个aa,汗~~~~):

点击查看原图

结果:

点击查看原图


方法一:

代码如下
SELECT a.id,a.SName,a.ClsNo,a.Score FROM aa a LEFT JOIN aa b ON a.ClsNo=b.ClsNo AND a.Score

拆开分析:

1、 LEFT JOIN aa b ON a.ClsNo=b.ClsNo AND a.Score

同一个班级(每个班级四个人),分数比当前学生高的记录,那就意味这成绩垫底的学生,将会产生三条记录

2、 group by a.id,a.SName,a.ClsNo,a.Score having count(b.id)<2

a.id,a.SName,a.ClsNo,a.Score可以代表一个学生(以学生分组),如果count(b.id)<2(成绩超过你的人不能多于2个),那就只剩第一第二了。


方法二:

代码如下
SELECT * FROM aa a WHERE 2>(SELECT COUNT(*) FROM aa WHERE ClsNo=a.ClsNo and Score>a.Score) ORDER BY a.ClsNo,a.Score DESC;

这个我觉得是比较有意思的,取每一条记录,判断同一个班级,大于当前成绩的同学是不是小于2个人。


方法三:

代码如下
SELECT * FROM aa WHERE id IN (SELECT id FROM aa WHERE ClsNo=a.ClsNo ORDER BY Score DESC LIMIT 2) ORDER BY a.ClsNo,a.Score DESC;

这种方式进过测试不通过,ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' ,不能在这几个子查询中使用limit。

人气教程排行