飞奔·慢行
===========================================================
mssql里一道题目的几种做法
===========================================================

求出每个学生最近的各科考试成绩

(学号) (课程号) (成绩)(考试日期)
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

kyle 发表于:2004.12.08 19:42 ::分类: ( dbms ) ::阅读:(586次) :: 评论 (0)

发表评论
标题

在此添加评论
表情符号: smile laughing tongue angry crying sad wassat wink

称呼

邮箱地址(可选)

个人主页(可选)

 authimage


自我介绍
切换风格
新闻聚合
博客日历
文章归档...
最新发表...
最新评论...
博客统计...
Blog信息
网站链接...