Re: [SQL ] grouping + sort 疑難一問

看板Database作者 (TeemingVoid)時間13年前 (2012/02/28 14:42), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《shanngmin (shanngmin)》之銘言: : 資料表範例如下(資料庫: MYSQL 5.0 ) : 欄位/資料 student_id(學生代號) / exam_id(小考編號) / 成績 : 10001 1 90 : 10001 2 85 : 10001 3 93 : 10002 1 91 : 10002 2 NULL (註:NULL = 缺考) : 10002 3 90 : 10003 1 75 : 10003 2 NULL : 10003 3 NULL : 我要怎麼下SQL,才能取到『每個學生最高分的前N筆』。 : 比如說10003 學生,如果取最高分的前兩筆,那他就是75, null。 不知您現在進度如何,如果還沒解決,不妨參考下列作法: use test; create table quiz ( student_id varchar(10) not null, exam_id int not null, score int null ); insert into quiz values ('10001', 1, 90), ('10001', 2, 85), ('10001', 3, 93), ('10002', 1, 91), ('10002', 2, null), ('10002', 3, 90), ('10003', 1, 75), ('10003', 2, null), ('10003', 3, null); select student_id, score from quiz q where ( select count(*) from quiz where student_id = q.student_id and score > q.score ) < 2 order by student_id, score desc; ↑↑↑↑↑↑↑↑↑↑ 抱歉,現在才留意到資料中有 null 值,請改用下列寫法,null 當成 0 來比較: select student_id, score from quiz q where ( select count(*) from quiz where student_id = q.student_id and coalesce(score, 0) > coalesce(q.score, 0) ) < 2 order by student_id, score desc; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.41.99.161

02/28 14:50, , 1F
看到大大分享給我的網頁跟範例了,謝謝大大無私的分享QQ
02/28 14:50, 1F

02/28 14:54, , 2F
^^
02/28 14:54, 2F
※ 編輯: TeemingVoid 來自: 114.41.99.161 (02/28 14:58)

02/28 14:59, , 3F
新版本我加上 coalesce 來處理 null 值。
02/28 14:59, 3F
文章代碼(AID): #1FJ7Sylr (Database)
文章代碼(AID): #1FJ7Sylr (Database)