有趣的SQL-搜尋前三名問題

flzhang發表於2017-05-16

今天看到這樣個問題,比如找出每個部門裡薪資在前三的所有員工資訊

具體資料和SQL是這樣的

WITH Employee AS(
       SELECT 1 Id, 'joe' Name,70000 SALARY,1 DepartmentId FROM DUAL UNION ALL
       SELECT 2 Id, 'Henry' Name,80000 SALARY,2 DepartmentId FROM DUAL UNION ALL
       SELECT 3 Id, 'Sam' Name,60000 SALARY,2 DepartmentId FROM DUAL UNION ALL
       SELECT 4 Id, 'Max' Name,90000 SALARY,1 DepartmentId FROM DUAL UNION ALL
       SELECT 5 Id, 'Janet' Name,69000 SALARY,1 DepartmentId FROM DUAL UNION ALL
       SELECT 6 Id, 'Randy' Name,85000 SALARY,1 DepartmentId FROM DUAL
      ),
      Department AS (
       SELECT 1 Id, 'IT' Name FROM DUAL UNION ALL
       SELECT 2 Id, 'Sales' Name FROM DUAL
      )
     
      SELECT T1.Name,T2.*
      FROM
           Department T1
          ,Employee   T2
      WHERE T1.Id= T2.DepartmentId
      AND 3>
      (
        SELECT COUNT(distinct T3.SALARY) RN
        FROM  Employee T3
        WHERE T2.DepartmentId = T3.DepartmentId
        AND T2.SALARY < T3.SALARY
      )
      ORDER BY T2.DEPARTMENTID,T2.SALARY

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750077/viewspace-2139157/,如需轉載,請註明出處,否則將追究法律責任。

相關文章