使用SQL中的连接查找部门的最高平均工资?

时间:2016-07-20 18:05:03

标签: sql

我有两个具有以下架构的表:

Table 1
-------
empID
empName


Table 2
-------
empID 
department  
salary

假设表是: 表1:

empID|empName
1    A
2    B
3    C
4    D
5    E
6    F
7    G
8    H
9    I
10   J

表2:

empID|department|salary
1    X    10
2    X    10
3    X    10
4    Y    5
5    Y    5
6    Y    5
7    Y    5
8    Y    5
9    Z    3
10   Z    3

我需要找到平均工资最高的部门名称,并将其与员工姓名一起显示。

我期待的输出是:

empName|department|salary
A         10        
B    X    10
C         10

这是一个面试问题,我正在从记忆中重新创造这个问题,所以它可能并不完美。在差距超过2年之后,我也在接受SQL。如果我错过了什么,请建议。

我形成的查询是:

SELECT
    table1.empName,
    TOP(1) AVG(table2.salary),
    table2.department
FROM
    table1
INNER JOIN
    table2
    ON table1.empID = table2.empID
GROUP BY
    table2.department

2 个答案:

答案 0 :(得分:1)

根据我从你的问题中得出的结论,我会这样做。

WITH department_rank AS
(
SELECT
    department,
    RANK() OVER(ORDER BY avg_salary DESC) AS avg_salary_rank
FROM
    (
    SELECT
        department,
        AVG(salary) AS avg_salary
    FROM
        table2
    GROUP BY
        department
    ) tbl
)

SELECT
    dept.department,
    emp.empID,
    emp.empName,
    dept.salary
FROM
    table2 dept
JOIN
    table1 emp
    ON  (emp.empID = dept.empID)
JOIN
    department_rank drnk
    ON  (drnk.department = dept.department)
    AND (drnk.avg_salary_rank = 1) --Top ranked department based on average salary

输出:

enter image description here

答案 1 :(得分:1)

您的语法看起来像SQL Server(" TOP 1")。在那个数据库中,我会做这样的事情:

d3.nest()
  .key(function(d) { return d.eventA; })
  .rollup(function(values) { return d3.sum(values, function(d) { return d.size; }) })
  .entries(dataset);

更通用的解决方案:

SELECT TOP (1) WITH TIES t1.empName, t2.salary, t2.department
FROM table1 t1 INNER JOIN
     table2 t2
     ON t1.empID = t2.empID
ORDER BY AVG(t2.salary) OVER (PARTITION BY t2.department) DESC;