很急!!!如何在一个表中查询出各部门薪资最高的前三名?

megin 2003-09-18 04:09:21
如同标题
...全文
501 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
amtyuranus 2003-09-18
  • 打赏
  • 举报
回复
楼主可以根据上面的语句加循环,然后组合起来就得到了,

加group by 与top 合用试试看
amtyuranus 2003-09-18
  • 打赏
  • 举报
回复
可惜楼上所有的答案都不能得到所有部门的前三名啊?

要一起出来怎么办呢?
WQLu 2003-09-18
  • 打赏
  • 举报
回复
select top 3 * from 你的表 tem where 薪资 in (select薪资 from 你的表 where 部门=tem.部门 order by 薪资 desc)

zjcxc 元老 2003-09-18
  • 打赏
  • 举报
回复
楼上几位的,这两种就可以了,楼主自行选择吧.:

--如果有并列的情况,会显示出并列的,可能超过3名.
select * from 你的表 tem where 薪资 in (select top 3 薪资 from 你的表 where 部门=tem.部门 order by 薪资 desc)



--要求表中有主键(例如人员编号),每个部门仅显示3条,即使有并列
假设你表的主键为ID
select * from 表 A
where ID in (select top 3 ID from 表 where 部门=A.部门 order by 薪资)

伍子V5 2003-09-18
  • 打赏
  • 举报
回复
我觉得你应该把条件说清楚一些
yujohny 2003-09-18
  • 打赏
  • 举报
回复
假设你表的主键为ID
select * from 表 A
where ID in (select top 3 ID from 表 where 部门=A.部门 order by 薪资 desc)
yujohny 2003-09-18
  • 打赏
  • 举报
回复
假设你表的主键为ID
select * from 表 A
where ID in (select top 3 ID from 表 where 部门=A.部门 order by 薪资)
pengdali 2003-09-18
  • 打赏
  • 举报
回复
select * from 你的表 tem where 薪资 in (select top 3 薪资 from 你的表 where 部门=tem.部门 order by 薪资 desc)
pengdali 2003-09-18
  • 打赏
  • 举报
回复
select * from 你的表 tem where 薪资 in (select top 3 薪资 from 你的表 where 部门=tem.部门 order by 薪资 desc)
swand 2003-09-18
  • 打赏
  • 举报
回复
用游标比较容易,看看我以前的例子:

declare @dept varchar(50)
declare @SalaryTable table
(Fname varchar(10),
Fsalary money,
Fdept varchar(50))

declare department_cursor cursor for
select distinct Fdept from yourDept
open department_cursor
fecth next from department_cursor into @dept
while(fecth_status=0)
begin
insert into @SalaryTable select top 3 Fname,Fsalary,Fdept from yourDept where Fdept=@dept order by Fsalary DESC
fecth next from department_cursor into @dept

end

select * from @SalaryTable

close department_cursor
dealloate department_cursor
pengdali 2003-09-18
  • 打赏
  • 举报
回复
select * from 你的表 tem where 薪资 in (select top 3 薪资 from 你的表 where 部门=tem.部门)

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧