Reputation: 53
Have this query (see below): I want to be able to use the ROW_NUMBER() function to return the record with the 2nd highest salary. I know how to use the function but I can't figure out where to put it since I have a subquery.
The query returns:
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
so, using the row number function I want to only return the record with sahi king. Thanks.
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;
Upvotes: 0
Views: 2258
Reputation: 12022
You can try the ROW_NUMBER
with ORDER BY Salary.Emp_Salary DESC
as below for this and if you need only the second highest then add a where
condition WHERE RowNo = 2
below.
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;
Upvotes: 4