分组条款获取最高薪雇员的姓名

时间:2013-03-21 05:03:10

标签: sql sql-server tsql

我有一个表有员工部门的员工,员工和工资。我想要一个查询来列出部门明智的最高工资和雇员的工资名称。

我知道这很简单。我用Google搜索,但找到了这样的答案,其中只列出了部门和工资

SELECT dept, SUM (salary)
FROM employee
GROUP BY dept; 

5 个答案:

答案 0 :(得分:4)

SELECT e1.*
FROM employee e1
JOIN (SELECT dept, MAX(salary) FROM employee GROUP BY dept) e2 ON
    e1.dept = e2.dept AND e1.salary = e2.salary

答案 1 :(得分:3)

SQL Server 2008支持Window Functions,可帮助您获得所需内容。

WITH recordList
AS
(
    SELECT  dept, employeeName, salary,
            DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) rn
    FROM    employee
)
SELECT dept, employeeName, salary
FROM   recordList
WHERE  rn = 1

答案 2 :(得分:3)

  SELECT e.*, d.deptname
    FROM employee e
    JOIN department d ON e.deptid = d.deptid
   WHERE EXISTS (SELECT 1
                   FROM employee e_in
                   JOIN department d_in ON e_in.deptid = d_in.deptid
                  WHERE d_in.deptid = d.deptid
               GROUP BY d_in.deptid
                 HAVING MAX(e_in.salary) = e.salary)

答案 3 :(得分:3)

这样就可以了。

SELECT E1.DEPT, E2.ENAME, E1.HIGHEST_SALARY
FROM
(SELECT DEPT, MAX(SALARY) HIGHEST_SALARY
FROM EMPLOYEE
GROUP BY DEPT) E1
INNER JOIN EMPLOYEE E2 ON E1.HIGHEST_SALARY = E2.SALARY
AND E1.DEPT = E2.DEPT

答案 4 :(得分:-1)

select * from (select salary,last_name,dense_rank()
over (order by salary desc)
sal_rank from employees) where sal_rank <=3;

全部......这是下面的输出:

SALARY LAST_NAME                   SAL_RANK
---------- ------------------------- ----------
 24000 King                               1
 17000 Kochhar                            2
 17000 De Haan                            2
 14000 Russell                            3