萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> mysql中GROUP BY分組取前N條記錄實現

mysql中GROUP BY分組取前N條記錄實現

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<b.Score group by a.id,a.SName,a.ClsNo,a.Score having count(b.id)<2 ORDER BY a.ClsNo,a.Score desc;

拆開分析:

<!--[if !supportLists]-->1、 <!--[endif]-->LEFT JOIN aa b ON a.ClsNo=b.ClsNo AND a.Score<b.Score

同一個班級(每個班級四個人),分數比當前學生高的記錄,那就意味這成績墊底的學生,將會產生三條記錄

<!--[if !supportLists]-->2、 <!--[endif]-->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。

 

copyright © 萬盛學電腦網 all rights reserved