Getting Started with Adobe After Effects - Part 6: Motion Blur
This module helps you to share, discuss and learn interview questions and answers of different technologies

Nth highest salaried employee in a department

Oct 26 2011 12:00AM by Ramireddy   

Question

How to get Nth highest salaried employee in a department Note: This is one of common questions asked in interview questions.

Answer

By using row_number() function, we can solve this problem.

DECLARE @Emp TABLE
(
    EmpId INT,
    DepartmentId INT,
    Salary INT
)
INSERT INTO @Emp VALUES 
(1,1,20),(2,1,30),(3,1,25),(4,1,35),(5,2,30),(6,2,25)

declare @n int = 2

;WITH cte AS
(
        SELECT EmpId,DepartmentId,Salary,
        ROW_NUMBER() OVER(PARTITION BY DepartmentId 
						ORDER BY Salary DESC) AS Seq 
		FROM @Emp
)
SELECT EmpId,DepartmentId,Salary FROM cte 
WHERE seq = 2

But row_number() is available from SQL Server 2005 only, there are chances that interviewers might ask for solution before SQL Server 2000.

Here is an comprehensive example in SQL Server 2000

DECLARE @Emp TABLE
(
    EmpId INT,
    DepartmentId INT,
    Salary INT
)

INSERT INTO @Emp VALUES (1,1,20)
INSERT INTO @Emp VALUES (2,1,30)
INSERT INTO @Emp VALUES (3,1,25)
INSERT INTO @Emp VALUES (4,1,35)
INSERT INTO @Emp VALUES (5,2,30)
INSERT INTO @Emp VALUES (6,2,25)

DECLARE @n INT 
SET @n = 2
SELECT EmpId,DepartmentId,Salary
FROM @emp E
WHERE (SELECT COUNT(*) 
		FROM @emp 
		WHERE DepartmentId = E.DepartmentId 
		AND Salary >= E.Salary) = @n

Read More..   [32134 clicks]

Published under: SQL Server Interview Questions ·  ·  ·  · 


Ramireddy
2 · 41% · 12972
0
Liked
 
0
Asked



Submit

Your Comment


Sign Up or Login to post a comment.

"Nth highest salaried employee in a department" rated 5 out of 5 by 1 readers
Nth highest salaried employee in a department , 5.0 out of 5 based on 1 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]