2014-06-20 123 views
0

我需要爲以下問題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 

問題的SQL查詢:對於每一個部門,我想找到誰是在該部門的最高級別員工。如果在特定部門的最高級別有兩個或兩個以上的emp。然後沒有記錄應該來爲部門

級別的層次是:VP>通用>祕書

所以我應該得到以下結果

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

對於IT而言,有在平VP沒有EMP 。下一級是通用汽車,但在這個級別有兩個倉庫,所以沒有選擇IT部門的記錄。

如果你能就此提出一個答案或方法,我將不勝感激。

+5

你有沒有嘗試過這麼遠嗎?請分享您嘗試的任何內容。 – evanv

+1

這可能有所幫助:http://stackoverflow.com/questions/5448354/mysql-get-max-values-of-groups – Dave

+1

**嘗試自己寫一些東西**,然後如果它不起作用,具體告訴我們什麼你這樣做,我們可以幫助你。 **你開始吧,然後我們幫忙。我們不會爲你寫信。**向我們展示你已經嘗試過的實際代碼,然後描述發生的事情和不正確的事情,然後我們可以從那裏幫助你。如果你只是先嚐試​​一下,你很可能會接近答案。 –

回答

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 
     ) 
0

爲Level創建另一個表,併爲等級字段。

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