单个表上的SQL查询

时间:2014-06-20 17:46:36

标签: mysql sql

我需要针对以下问题的SQL查询

Table: EMPLOYEE  
DeptCode   Level  EmpID Name  
Mkt    VP      1    JOHN  
Mkt    GM      2    BOB  
Mkt    CLERK   3    TIM  
IT     GM      4    BILLY  
IT     GM      5    JESSICA  
IT     CLERK   6    MONICA  
HR     VP      7    NIKITA  
HR     GM      8    TOM  
HR     GM      9    HARRY  

问题:对于每个部门,我想找到该部门最高级别的员工。如果特定部门中最高级别有2个或更多的emp。那个部门不应该有记录

Level的层次结构是:VP> GM>秘书

所以我应该得到以下结果

DeptCode    Level   EmpID   Name  
Mkt VP  1   JOHN  
HR  VP  7   NIKITA

对于IT,VP级别没有emp。下一级是GM,但是这个级别有两个emp,因此没有为IT部门选择记录

如果你能就此提出答案或方法,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

SELECT  e.*
FROM    (
        SELECT  DISTINCT
                deptCode
        FROM    employee
        ) ed
JOIN    employee e
ON      e.empId =
        (
        SELECT  empId
        FROM    employee ei
        WHERE   ei.deptCode = ed.deptCode
        ORDER BY
                FIND_IN_SET(level, 'VP,GM,CLERK')
        LIMIT 1
        )
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    employee eo
        WHERE   (eo.deptCode, eo.level) = (e.deptCode, e.level)
                AND eo.empId <> e.empId
        )

答案 1 :(得分:0)

为Levels创建另一个表,其中包含Rank。

Level   Rank
VP      1
GM      2
CLERK   3

然后创建一个如下所示的视图(即vHighestRankPerDept):

SELECT Levels.Level AS HighestLevel, t.DeptCode
FROM (SELECT MIN(Levels.Rank) AS Highest, Employee.DeptCode
      FROM Levels INNER JOIN Employee ON Employee.Level = Levels.Level
      GROUP BY Employee_1.DeptCode) AS t
INNER JOIN Levels ON Levels.Rank = t.Highest

然后:

SELECT Employee.DeptCode, Employee.Level, MAX(Employee.EmpID) AS EmpID, MAX(Employee.Name) AS Name
FROM Employee
INNER JOIN vHighestRankPerDept ON vHighestRankPerDept.DeptCode = Employee.DeptCode
  AND Employee.Level = vHighestRankPerDept.HighestLevel
GROUP BY Employee.DeptCode, Employee.Level
HAVING COUNT(Employee.Level) = 1