我有这张桌子。我想以最高薪水选择每个职业的所有员工。
我尝试了一切,但似乎没有任何工作。 以下查询结果错误。
SELECT * FROM Employee WHERE EmployeeID IN (
SELECT EmployeeID FROM Employee HAVING MAX(Salary) = Salary GROUP BY Profession)
答案 0 :(得分:3)
您可以使用ROW_NUMBER
窗口功能
SELECT *
FROM (SELECT *,
Row_number()OVER (PARTITION BY Profession ORDER BY Salary DESC) rn
FROM Employee) a
WHERE rn = 1
注意:当一个职业的最高薪水达到平局时,如果您需要领带记录,则只返回一个,然后使用DENSE_RANK
SELECT *
FROM (SELECT *,
Dense_rank()OVER (PARTITION BY Profession ORDER BY Salary DESC) rn
FROM Employee) a
WHERE rn = 1
如果你想修复你的子查询然后(将返回平局记录)
SELECT *
FROM Employee e1
WHERE Salary = (SELECT Max(Salary)
FROM Employee e2
WHERE e1.Profession = e2.Profession)
或
SELECT *
FROM Employee e1
WHERE EXISTS (SELECT 1
FROM Employee e2
WHERE e1.Profession = e2.Profession
HAVING Max(Salary) = e1.Salary)
答案 1 :(得分:2)
SELECT *
FROM (
SELECT *
, ROW_NUMBER() OVER (PARTITION BY Profession ORDER BY Salary DESC) rn
FROM Employee
) x
WHERE x.rn = 1
答案 2 :(得分:0)
尝试这个简单的查询!
SELECT
EmployeeID ,
EmployeeName ,
Profession ,
max(Salary) AS 'Salary'
FROM
Employee
GROUP BY
Profession
答案 3 :(得分:-1)
SELECT *
FROM employees
WHERE salary IN (SELECT MAX(salary)
FROM Employees
GROUP BY Profession)