id ename
----------- ----------
1 apv
2 sug
3 raj
4 ram
5 sam
6 apv1
7 sug1
8 raj1
9 ram1
10 sam1
dept salary id
----- ----------- -----------
a 1000 1
b 2000 2
c 3000 3
d 5000 4
e 7000 5
a 20000 6
b 500 7
c 5000 8
a 1000 9
b 90000 10
如何从每个部门返回Max(salary)
以及谁获得该薪水的详细信息?
(选择id,ename,dept,salary)
答案 0 :(得分:3)
select mm, d1.dept, d1.id, ename from DEPT D1,
(select max(salary) mm, dept from DEPT group by dept) D2, EMP
where D2.mm=d1.salary and d2.dep=d1.dept
EMP.ID=DEPT.ID
答案 1 :(得分:1)
declare @Emp table (id int, ename varchar(4))
declare @Dept table (dept char(1), salary int, id int)
insert into @Emp values
(1, 'apv'),
(2, 'sug'),
(3, 'raj'),
(4, 'ram'),
(5, 'sam'),
(6, 'apv1'),
(7, 'sug1'),
(8, 'raj1'),
(9, 'ram1'),
(10, 'sam1')
insert into @Dept values
('a', 1000, 1),
('b', 2000, 2),
('c', 3000, 3),
('d', 5000, 4),
('e', 7000, 5),
('a', 20000, 6),
('b', 500, 7),
('c', 5000, 8),
('a', 1000, 9),
('b', 90000, 10)
;with cte as
(
select
id,
salary,
dept,
rank() over(partition by dept order by salary desc) as rn
from @Dept
)
select
e.ename,
e.id,
c.salary,
c.dept
from cte as c
inner join @Emp as e
on c.id = e.id
where rn = 1
结果
ename id salary dept
----- ----------- ----------- ----
apv1 6 20000 a
sam1 10 90000 b
raj1 8 5000 c
ram 4 5000 d
sam 5 7000 e
答案 2 :(得分:1)
首先按部门预先查询,然后回到同一部门并匹配工资。从该表中,您可以绑定到employee表。该版本将允许同一部门中具有相同薪水的多个人退出...例如:部门X中有5人获得75,000。
SELECT
d1.Dept,
d1.Salary,
Emp.id,
Emp.name
from
( SELECT
dept,
MAX(salary) MaxSal
from
Dept
group by
dept ) ByDept
join Dept d1
ON ByDept.dept = d1.dept
and ByDept.MaxSal = d1.Salary
join Emp
ON d1.id = Emp.id
答案 3 :(得分:0)
我不知道我是否理解你,但你可以尝试类似的事情:
SELECT id, ename, dept, MAX(salary) AS salary
FROM Dept_Table AS d
LEFT JOIN Emp_Table AS e
ON e.id = d.id
GROUP BY dept
答案 4 :(得分:0)
select dept.dept, max(dept.salary), emp.id, emp.ename
from emp inner join dept on emp.id=dept.id
group by dept.dept, emp.id, emp.ename
应该这样做,只要知道如果同一个部门中的两个人有相同的工资而且这是最高工资,你就会让两个人都外出。
答案 5 :(得分:0)
选择emp.ename,dept.dept,max(dept.salary)from dept left join emp on dept.id = emp.id group by dept.dept