有下表:姓名 科目 成绩 考试时间
张三 语文 80 2011/4/10
李四 数学 85 2011/4.11
王五 化学 90 2011/4.12
张三 物理 100 2011/4.13
李四 英语 95 2011/4.14
王五 历史 80 2011/4.15
请问如何查询每一个学生最后一次考试时间的成绩?
谢谢!
张三 语文 80 2011/4/10
李四 数学 85 2011/4.11
王五 化学 90 2011/4.12
张三 物理 100 2011/4.13
李四 英语 95 2011/4.14
王五 历史 80 2011/4.15
请问如何查询每一个学生最后一次考试时间的成绩?
谢谢!
where not exists(select 1 from tb where 姓名=a.姓名 and 考试时间>a.考试时间)
select t.* from tb t where not exists (select 1 from tb where 姓名 = t.姓名 and 考试时间 > t.考试时间)
join
(
select 姓名, max(考试时间) 考试时间 from tbgroup by 姓名
) s
on t.姓名=s.姓名and t.考试时间=s.考试时间select t.* from tb t
left join
(select * from tb) S
on t.姓名=s.姓名
where S.考试时间<t.考试时间
use tempdb;
/*
create table t1
(
姓名 nvarchar(10) not null,
科目 nvarchar(10) not null,
成绩 int not null,
考试时间 nvarchar(20) not null
);
insert into t1(姓名,科目,成绩,考试时间)
values
('张三','语文',80,'2011/4/10'),
('李四','数学',85,'2011/4.11'),
('王五','化学',90,'2011/4.12'),
('张三','物理',100,'2011/4.13'),
('李四','英语',95,'2011/4.14'),
('王五','历史',80,'2011/4.15');
*/
select t1.姓名,
--MAX(t1.科目) as [科目],MAX(t1.成绩) as [成绩],
MAX(CAST(replace(考试时间,'.','/') as date)) as [考试时间]
from t1
group by t1.姓名;
create table mm(姓名 varchar(10), 科目 varchar(10),成绩 int,考试时间 datetime)
insert mm
select '张三', '语文' ,80 ,'2011/4/10' union all
select '李四', '数学', 85 ,'2011/4/11' union all
select '王五' ,'化学' ,90, '2011/4/12' union all
select '张三', '物理', 100, '2011/4/13' union all
select '李四', '英语', 95, '2011/4/14' union all
select '王五', '历史' ,80 ,'2011/4/15'--下面三种查询都可以
--第一种
select a.* from mm a where not exists (select * from mm b where a.姓名=b.姓名 and b.考试时间>a.考试时间)
go
--第二种
select a.* from mm a where a.考试时间>= all (select 考试时间 from mm b where a.姓名=b.姓名)
go
--第三种
select a.* from mm a where a.考试时间= (select max(考试时间) from mm b where a.姓名=b.姓名) /*
张三 物理 100 2011-04-13 00:00:00.000
李四 英语 95 2011-04-14 00:00:00.000
王五 历史 80 2011-04-15 00:00:00.000
*/