现在有一个表,有3个字段,部门(department),姓名(name),分数(credit)
比如
部门, 姓名, 分数
质量部 张山 100
软件部 李四 100
质量部 王五 100
质量部 赵六 99
软件部 粱起 98
软件部 刘开 100我想取得每个部门考的分数最高的那个人,如果该部门有两个人的分数并列是第一的话,随便只取一个,
如上面的结果就是质量部 张山 100
软件部 刘开 100
这是一个正确的答案
或者
质量部 张山 100
软件部 李四 100
答案可能有多个,但是我只想随便取一个,请问这个SQL语句该怎么写
比如
部门, 姓名, 分数
质量部 张山 100
软件部 李四 100
质量部 王五 100
质量部 赵六 99
软件部 粱起 98
软件部 刘开 100我想取得每个部门考的分数最高的那个人,如果该部门有两个人的分数并列是第一的话,随便只取一个,
如上面的结果就是质量部 张山 100
软件部 刘开 100
这是一个正确的答案
或者
质量部 张山 100
软件部 李四 100
答案可能有多个,但是我只想随便取一个,请问这个SQL语句该怎么写
where A.分数 = B.分数 and A.部门=b.部门
and 其他条件
create table te(department varchar(10),name varchar(10),credit int)
insert te select '质量部','张山',100
insert te select '软件部','李四',100
insert te select '质量部','王五',100
insert te select '质量部','赵六',99
insert te select '软件部','粱起',98
insert te select '软件部','刘开',100
go
--语句
select department,max(name) as name,max(credit) as credit from te group by department
go
select department,min(name) as name,max(credit) as credit from te group by department
go
--删表
drop table te
go
insert te select '质量部','张山',100
insert te select '软件部','李四',100
insert te select '质量部','王五',100
insert te select '质量部','赵六',99
insert te select '软件部','粱起',98
insert te select '软件部','刘开',100
go
select *,id=identity(int,1,1) into #i from teselect department,name, credit from #i where id in (select min(id) id from #i group by department)
insert into @T
select '质量部', '张山', 100 union
select '软件部', '李四', 100 union
select '质量部', '王五', 100 union
select '质量部', '赵六', 99 union
select '软件部', '粱起', 98 union
select '软件部', '刘开', 100select dept,
max(name) as name,
score
from @t a
where
not exists( select 1 from @t b where a.dept = b.dept and a.score < b.score)
group by dept ,score
insert into @T
select '质量部', '张山', 100 union
select '软件部', '李四', 100 union
select '质量部', '王五', 100 union
select '质量部', '赵六', 99 union
select '软件部', '粱起', 98 union
select '软件部', '刘开', 100
select * from @t a where [name] in(select top 1 [name] from @t where a.dept=dept order by score desc)