1. 程式人生 > >sql 查詢最新的資料或某個最大值得資料

sql 查詢最新的資料或某個最大值得資料

-- 新建分數表,該表記錄學生最近幾天本課程的所有分數
create table scores(
id int identity(1,1),
 name nvarchar(50) null,
 score float null,
 sdate nvarchar(50) null
)

-- 插入 li 同學本課程這幾天的考試分數資訊
insert into scores values('li',80,'2018-10-10 10:01:20')
insert into scores values('li',89,'2018-10-12 10:01:20')
insert into scores values('li',100,'2018-10-13 10:01:20')
insert into scores values('li',72,'2018-10-14 10:01:20')
insert into scores values('li',89,'2018-10-15 10:01:20')
-- 插入 liu 同學本課程這幾天的考試分數資訊
insert into scores values('liu',88,'2018-10-10 10:01:20')
insert into scores values('liu',90,'2018-10-12 10:01:20')
insert into scores values('liu',98,'2018-10-13 10:01:20')
insert into scores values('liu',88,'2018-10-14 10:01:20')
insert into scores values('liu',89,'2018-10-15 10:01:20')

-- 查詢每個同學分數最高的一次考試資訊
select * from scores where score=(select max(score)  from scores  s where s.name=scores.name);

-- 查詢每個同學最後一次的考試資訊
select * from scores where sdate = (select max(sDate) from scores s where s.name=scores.name );