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

來源:互聯網
上載者:User
 代碼如下 複製代碼

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。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.