看板 Database 關於我們 聯絡資訊
※ 引述《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
shanngmin:看到大大分享給我的網頁跟範例了,謝謝大大無私的分享QQ 02/28 14:50
TeemingVoid:^^ 02/28 14:54
※ 編輯: TeemingVoid 來自: 114.41.99.161 (02/28 14:58)
TeemingVoid:新版本我加上 coalesce 來處理 null 值。 02/28 14:59