Re: [SQL ] grouping + sort 疑難一問
※ 引述《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
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
02/28 14:59, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):