作者TeemingVoid (TeemingVoid)
看板Database
标题Re: [SQL ] grouping + sort 疑难一问
时间Tue Feb 28 14:42:01 2012
※ 引述《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
1F:推 shanngmin:看到大大分享给我的网页跟范例了,谢谢大大无私的分享QQ 02/28 14:50
2F:→ TeemingVoid:^^ 02/28 14:54
※ 编辑: TeemingVoid 来自: 114.41.99.161 (02/28 14:58)
3F:→ TeemingVoid:新版本我加上 coalesce 来处理 null 值。 02/28 14:59