我有一个表Employee,其内容如下
------------------------------------------------------------------- Name Department Salary ------------------------------------------------------------------- Hemant PTS 100 Gunjan PTS 101 Amol ADM 50 Parthiv ADM 60 -------------------------------------------------------------------
我想写一个SINGLE查询来显示PTS最高工资消费者群体的名称。 换句话说,查询的输出应该是Gunjan和Parthiv来自不同的部门并且在该部门获得最高薪水。
------------------------------------------------------------------- Name Department Salary ------------------------------------------------------------------- Gunjan PTS 101 Parthiv ADM 60 -------------------------------------------------------------------
以下查询工作正常
SELECT E.Department,MAX(E.Salary) FROM
Employee E
GROUP BY Department;
但是如何选择名称以及部门和Max(薪资)?
答案 0 :(得分:4)
由于你没有提到任何RDBMS,下面的这个查询几乎可以在任何RDBMS上工作(但不是我猜的全部)
SELECT a.*
FROM Employee a
INNER JOIN
(
SELECT Department, MAX(Salary) Max_Val
FROM Employee
GROUP BY Department
) b ON a.Department = b.Department AND
a.Salary = b.Max_Val
输出
╔═════════╦════════════╦════════╗
║ NAME ║ DEPARTMENT ║ SALARY ║
╠═════════╬════════════╬════════╣
║ Gunjan ║ PTS ║ 101 ║
║ Parthiv ║ ADM ║ 60 ║
╚═════════╩════════════╩════════╝