从不同的部门获得最高工资而不使用group by,join

时间:2013-12-24 09:21:38

标签: mysql sql

---------------------------
    dept | salary | name  
---------------------------
    1    | 10000  | ch1
---------------------------
    2    | 20000  | ch2
---------------------------
    2    | 25000  | ch3
---------------------------
    2    | 30000  | ch4
---------------------------
    1    | 15000  | xyz
---------------------------
    1    | 17000  | wer

我想从每个部门获得最高工资而不使用任何子查询或加入或分组。这可能吗?

1 个答案:

答案 0 :(得分:4)

如果不使用GROUP BYJOIN或子查询,部门无法获得最高薪水,您也无法在不使用SELECTFROM。听起来你要么打高尔夫球,要么误解GROUP BY或JOIN的工作方式。以下4种方法中的任何一种都会按部门提供最高工资,最后3种方法允许您从表中检索所有列:

1.Simple Group By

SELECT  Dept, MAX(Salary) AS MaxSalary
FROM    T
GROUP BY Dept;

2.分组并加入主表

SELECT  T.Dept, T.Salary, T.Name
FROM    T
        INNER JOIN
        (   SELECT  Dept, MAX(Salary) AS MaxSalary
            FROM    T
            GROUP BY Dept
        ) T2
            ON t2.Dept = T.Dept
            AND T2.MaxSalary = T.Salary;

第3。使用LEFT JOIN / IS NULL

SELECT  T.Dept, T.Salary, T.Name
FROM    T
        LEFT JOIN T T2
            ON T2.Dept = T.Dept
            AND T2.Salary > T.Salary
WHERE   T2.Dept IS NULL;

<强> 4。使用NOT EXISTS

SELECT  T.Dept, T.Salary, T.Name
FROM    T
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    T T2
            WHERE   T2.Dept = T.Dept
            AND     T2.Salary > T.Salary
        );

<强> Examples on SQL Fiddle