June 23, 2010 at 11:55 pm
The table structure is
Salary Id
7000 222
5000 333
3600 555
1200 777
6700 888
In an interview I was asked to select 4th highest salary. How to write query for this?
June 24, 2010 at 12:00 am
Investigate the windowing functions in Books on line
June 24, 2010 at 12:21 am
SELECT MIN([Salary]) FROM [SSIS].[dbo].[Salary] where salary in (SELECT DISTINCT TOP 4 [Salary] FROM [SSIS].[dbo].[Salary] ORDER BY [Salary] DESC )
Hope this helps
Raunak J
June 24, 2010 at 1:27 am
Thank u Raunak. Perfect Answer 🙂
June 24, 2010 at 2:01 am
sachinrshetty (6/24/2010)
Thank u Raunak. Perfect Answer 🙂
You interviewer is not going to say the same to you as Thank you Sachin. Perfect Answer. Be prepared for more detailed questions on the same topic. He may ask you as to What will happen if you have two or more people with same salary? How do you rank them? Do you assign them same rank or different rank.
If you don't prepare for questions like that, you might be stumped. Thats why Dave advised you to have a look at Windowing Functions. There are some functions like ROW_NUMBER(), RANK(), DENSE_RANK() which you can use for different situations. Have a look at these functions if you have time and this will help you to prepare better for the interview.
This is not to say that Raunak solution is wrong. It was a good solution and was new to me. So, Thanks Raunak. But you would be better equiped for the interview if you get into the details a bit.
How to post data/code on a forum to get the best help - Jeff Moden
http://www.sqlservercentral.com/articles/Best+Practices/61537/
June 24, 2010 at 2:05 am
Well said....
Raunak J
June 24, 2010 at 2:19 am
June 25, 2010 at 6:02 am
The query can be even shorter (and faster) if you like:
SELECT MIN([Salary]) FROM (SELECT DISTINCT TOP 4 [Salary] FROM [SSIS].[dbo].[Salary] ORDER BY [Salary] DESC) q
But are you sure that you've been asked to select the 4th highest salary? I would think it is a bit non-life issue. I would ask you to select the employee with the 4th highest salary!
The above approach would not be the best in this case and I would also suggest you to have a look ranking functions...
June 25, 2010 at 6:02 am
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply