Citigroup Interview Question
Financial Software DevelopersCountry: United States
This gives the correct solution. But if you check the execution plan for this query, it takes an aweful lot of time to execute.
Best would be to use ranking functions as below:
Select top 1 Salary.Employee_Salary from (
select dense_rank() over (order by Employee_Salary desc) as 'Salary_Rank', Employee_Salary from Employee) as Salary
where Salary.[Salary_Rank] = N
The logic is if some number is top N in table then there will be (n-1) number more than that in table take a example
you have 9,8,7,6 in table as id and Top 2 will have only one number more than that so it is used
1 = SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
--Below query is used to find out 3rd maximum salary.Replace the below subquery with --the number you want to.
SELECT TOP (1) EMP,SALARY FROM YOURTABLE
WHERE SALARY NOT IN (SELECT TOP(2) SALARY FROM YOURTABLE ORDER BY SALARY DESC)
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal < = b.sal);
This gives the correct solution. But if you check the execution plan for this query, it takes an aweful lot of time to execute.
Best would be to use ranking functions as below:
Select top 1 Salary.Employee_Salary from (
select dense_rank() over (order by Employee_Salary desc) as 'Salary_Rank', Employee_Salary from Employee) as Salary
where Salary.[Salary_Rank] = N
SELECT *
- Dhass April 20, 2013FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)