成绩表序号 姓名 分数 学科
1 小王 80 数学
2 小李 75 数学
4 小赵 95 英语
5 小王 70 英语
6 小李 80 英语
7 小王 90 语文
8 小李 80 语文现在要用sql语句搜索每一课成绩的最高分
要具有如下的样子
序号 姓名 学科 成绩
1 小王 数学 80
4 小赵 英语 95
7 小王 语文 90请大虾指点,谢谢
1 小王 80 数学
2 小李 75 数学
4 小赵 95 英语
5 小王 70 英语
6 小李 80 英语
7 小王 90 语文
8 小李 80 语文现在要用sql语句搜索每一课成绩的最高分
要具有如下的样子
序号 姓名 学科 成绩
1 小王 数学 80
4 小赵 英语 95
7 小王 语文 90请大虾指点,谢谢
Select * From T1 A
Where ID in
(Select Top 1 Id From T1 Where 学科=A.学科 Order by 分数 Desc)
from 成绩表 a
where id in
(
select top 1 with ties id from 成绩表 where 学科=a. 学科 order by 成绩 desc
)
INNER JOIN
(SELECT 学科,MAX(分数) m FROM 成绩表) b
ON a.学科=b.学科 AND a.分数=m未测试可能有手误
INNER JOIN
(SELECT 学科,MAX(分数) m FROM 成绩表 GROUP BY 学科) b
ON a.学科=b.学科 AND a.分数=m上面打忘了
Declare @t Table(Id Int,Name Varchar(20),Score Int,Subject varchar(10))
Insert @t Select 1,'小王',80,'数学'
Union all Select 2,'小李',75,'数学'
Union all Select 4,'小赵',95,'英语'
Union all Select 5,'小王',70,'英语'
Union all Select 6,'小李',80,'英语'
Union all Select 7,'小王',90,'语文'
Union all Select 8,'小李',80,'语文'
--Test
Select * From @t A
Where Not Exists
(Select 1 From @t Where Subject=A.Subject and Score>A.score)
create table test
(序号 int identity(1,1) not null,
姓名 varchar(20),
分数 int,
学科 varchar(10))insert test(姓名,分数,学科)
select '小王',80,'数学'
union all select '小李',75,'数学'
union all select '小赵',95,'英语'
union all select '小王',70,'英语'
union all select '小李',80,'英语'
union all select '小王',90,'语文'
union all select '小李',80,'语文'select * from testselect *
from test a
where 序号 in
(select top 1 序号 from test where 学科=a.学科 order by 分数 desc)drop table test
create table #(id int , name varchar(20) , score int , subject varchar(20))
insert into #
select 1 , '小王' , 80, '数学' union
select 2 , '小李' , 75 , '数学' union
select 4 , '小赵' , 95 , '英语' union
select 5 , '小王' , 70 , '英语' union
select 6 , '小李' , 80 , '英语' union
select 7 , '小王' , 90 , '语文' union
select 8 , '小李' , 80, '语文'
1 select * from # a
where not exists(select 1 from # b where a.subject = b.subject and a.score < b.score)2 select * from # a where score in
(select max(score) from # b where a.subject = b.subject )