连接表中的多个最大值

时间:2015-04-25 13:12:45

标签: sql postgresql

我需要编写SQL查询,分别从每个部门获得薪酬最高的员工,并返回员工的姓名和薪酬以及他们所在的部门名称。

    employees
    +----+-------+------+---------------+
    | id | name  | pay  | department_id |
    +----+-------+------+---------------+
    | 1  | Bob   | 1200 | 1             |
    | 2  | Rob   | 600  | 2             |
    | 3  | Tom   | 800  | 2             |
    | 4  | Pam   | 900  | 1             |
    | 5  | Dave  | 1200 | 1             |
    +----+-------+------+---------------+

    departments
    +----+-----------+
    | id | name      |
    +----+-----------+
    | 1  | IT        |
    | 2  | Marketing |
    +----+-----------+

这个查询只返回表中薪酬最高的每个部门的第一个员工,但我希望得到薪水最高的所有员工,在这种情况下,来自IT的Bob和Dave以及来自市场营销的Tom

  SELECT d.name,e.name,e.pay FROM employees e JOIN departments d 
  ON e.department_id = d.id GROUP BY d.id HAVING MAX(e.pay)

正确的结果应该是:

+-----------+-------+------+
| IT        | Bob   | 1200 |
| IT        | Dave  | 1200 |
| Marketing | Tom   | 800  |
+-----------+-------+------+

4 个答案:

答案 0 :(得分:2)

重新定义“拥有最高薪水”是:“应该没有人有更高的薪水”(在同一部门内)

SELECT d.name, e.name,e.pay
FROM employees e
JOIN departments d ON e.department_id = d.id
WHERE NOT EXISTS (
    SELECT 42 FROM employees x
    WHERE x.department_id = e.department_id -- same dept
    AND x.pay > e.pay                       -- higher pay
    );

答案 1 :(得分:0)

需要子查询,这适用于大多数数据库但不了解MySQL。

SELECT
  d.name,
  e.name,
  e.pay
FROM
  employees e JOIN departments d
    ON e.department_id = d.id
WHERE
  (d.id, e.pay) =
    (SELECT
       d.id,
       MAX(e.pay)
     FROM
       employees e JOIN departments d
       ON e.department_id = d.id
     GROUP BY
       d.id)

答案 2 :(得分:0)

试试这个

SELECT d.name,e.name,e.pay FROM employess e JOIN departments d 
  ON e.deparment_id = d.id where e.pay in (select max(pay) from employess group by id) 

SQL Fiddle

答案 3 :(得分:0)

为此目的还有window function rank()

$(document).ready(function(){
$('#Browse').change(function(){ 

    var outputImg = document.getElementById('output');



           outputImg.src = URL.createObjectURL(event.target.files[0]);

    window.open("ShowImage.html?imgDetails="+outputImg.src, "Image","width=200, height=100");
});
});

//window.opener.location.href

SQL Fiddle.

仅当SELECT d.name AS department, e.name AS person, e.pay FROM ( SELECT department_id AS id, name, pay , rank() OVER (PARTITION BY department_id ORDER BY pay DESC NULLS LAST) AS rnk FROM employees ) e JOIN departments d USING (id) WHERE rnk = 1; 可以为NULL时才需要

NULLS LAST

除此之外:“name”和“id”几乎不是有用的标识符,您可以从这个简单的查询中看到。我必须使用列别名来做任何有用的事情。