发表于: 2004.12.08 19:42
分类: dbms
出处: http://kyle.itpub.net/post/1626/9123
---------------------------------------------------------------
求出每个学生最近的各科考试成绩
(学号) (课程号) (成绩)(考试日期)
1 、 1 、 70、2004-1-1
2 、 1 、 60、2004-1-1
3、 1 、 60、2004-1-1
1 、 2 、 80、2004-3-1
2 、 2 、 90、2004-3-1
3、 2、 100、2004-3-1
1、 1 、 71、2004-4-1
2、 1 、 80、2004-4-1
3 、 1 、 66、2004-4-1
如果学号为1的,结果为
1 、 2 、 80、2004-3-1
1、 1 、 71、2004-4-1
下面三种做法用到exists和group by
----------------------------------------------------------------------------------------------
--建表
create table exam_score(id int null, class int null, score int null, exam_date datetime null)
go
insert into exam_score
select 1,1,70, '1/1/2004'
insert into exam_score
select 2,1,60,'1/1/2004'
insert into exam_score
select 3,1,60,'1/1/2004'
insert into exam_score
select 1,2,80,'3/1/2004'
insert into exam_score
select 2,2,90,'3/1/2004'
insert into exam_score
select 3,2,100,'3/1/2004'
insert into exam_score
select 1,1,71,'4/1/2004'
insert into exam_score
select 2,1,80,'4/1/2004'
insert into exam_score
select 3,1,66,'4/1/2004'
go
----------------------------------------------------------------------------------------------
--我的做法:
select distinct * from exam_score a where exists (select *
from exam_score
where a.id=id and a.class=class having max(exam_date)=a.exam_date)
----------------------------------------------------------------------------------------------
--其他两位朋友的做法:
--A朋友:
select distinct* from exam_score a
where not exists (select 1 from exam_score b
where a.id = b.id and a.class = b.class and a.exam_date < b.exam_date)
order by a.id, a.class
----------------------------------------------------------------------------------------------
--B朋友:
select distinct a.* from exam_score a, (select id,class,max(exam_date) exam_date from exam_score group by id, class) b
where a.id=b.id and a.class=b.class and a.exam_date=b.exam_date











