2016-11-08 44 views
0

有此查詢(請參閱下面): 我希望能夠使用ROW_NUMBER()函數返回薪水第二高的記錄。我知道如何使用該函數,但由於我有一個子查詢,我無法弄清楚該把它放在哪裏。使用ROW_NUMBER()查找Sql Server中的第二高

查詢返回:

Yuriana Hagasawa NULL China Project Manager 56000.00 
Venessa Katarina Cameron Denmark  Tech Lead 185000.00 
Sahi King NULL Denmark  Design Engineer 156000.00 
Chen Chen NULL Andorra  Project Manager 76000.00 

因此,使用行數函數我只想與SAHI王者歸來的記錄。謝謝。

SELECT C.[First Name], 
C.[Last Name], 
C.[Middle Name], 
C.[Country Name], 
C.[Designation Name], 
Salary.Emp_Salary AS 'Current Salary' 
    FROM 
    (
    SELECT 
     Emp_First_Name AS "First Name", 
     Emp_Last_Name AS "Last Name", 
     Emp_Middle_Name AS "Middle Name", 
     Country_Name AS "Country Name", 
     Desig_Name as "Designation Name", 
     MAX(Emp_Salary_Change_Year) AS "Change Year" 

     FROM Employee_Details AS e 

    INNER JOIN Country AS co ON e.Emp_Country_Id = co.Country_Id 
    INNER JOIN State AS s ON e.Emp_State_Id = s.State_Id 
    INNER JOIN Designation AS d ON e.Desig_Id = d.Desig_Id 
    INNER JOIN Salary AS sa ON e.Emp_Id = sa.Emp_Id 

    GROUP BY Emp_First_Name, Emp_Last_Name, 
    Emp_Middle_Name, Country_Name, Desig_Name) AS C 
    INNER JOIN Salary ON C.[Change Year] = Salary.Emp_Salary_Change_Year; 

回答

3

你可以嘗試用ROW_NUMBERORDER BY Salary.Emp_Salary DESC下面這一點,如果你只需要在第二個最高再增加一個where條件如下WHERE RowNo = 2

SELECT * FROM (
SELECT C.[First Name], 
    C.[Last Name], 
    C.[Middle Name], 
    C.[Country Name], 
    C.[Designation Name], 
    Salary.Emp_Salary AS 'Current Salary', 
    ROW_NUMBER() OVER (ORDER BY Salary.Emp_Salary DESC) As RowNo 
     FROM 
     (
     SELECT 
      Emp_First_Name AS "First Name", 
      Emp_Last_Name AS "Last Name", 
      Emp_Middle_Name AS "Middle Name", 
      Country_Name AS "Country Name", 
      Desig_Name as "Designation Name", 
      MAX(Emp_Salary_Change_Year) AS "Change Year" 

      FROM Employee_Details AS e 

     INNER JOIN Country AS co ON e.Emp_Country_Id = co.Country_Id 
     INNER JOIN State AS s ON e.Emp_State_Id = s.State_Id 
     INNER JOIN Designation AS d ON e.Desig_Id = d.Desig_Id 
     INNER JOIN Salary AS sa ON e.Emp_Id = sa.Emp_Id 

     GROUP BY Emp_First_Name, Emp_Last_Name, 
     Emp_Middle_Name, Country_Name, Desig_Name) AS C 
     INNER JOIN Salary ON C.[Change Year] = Salary.Emp_Salary_Change_Year) t 
WHERE RowNo = 2; 
+0

RowNo = 2去哪?我試着把它放在最後,並得到語法錯誤 –

+0

我已更新查詢,請看看 – Aruna

+0

謝謝它的工作。 –