How to find the first 5 highest salaried employees in each department

How to find the first 5 highest salaried employees in each department

Given employee table in scott user, how will I find the first 5 highest salaried employees in each dept.?

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

Assuming this is SQL/Server 7, use the SELECT TOP option to select the top 5 in each department in a correlated subselect --

select *
  from scott.employee X
 where salary in
       (select top 5 salary
          from scott.employee
         where dept = X.dept
       order by salary desc)
 order by dept, salary desc

Sorry, I'm not 100% sure this will work because I do not have access to SQL/Server to test this. I'm not certain the syntax for referring to scott's employee table is correct.

Note that the ORDER BY in the subselect is descending, so that the TOP function will pick the five highest salaries. The ORDER BY in the outer query sorts the results by highest salaries within department.

By the way, both I and Craig Mullins, another of searchDatabase.com's database experts, have written web page articles which discuss the "Top Ten" problem --

The "Top Ten" Problem by Craig S. Mullins
http://www.craigmullins.com /ssu_0900.htm

Top Ten SQL by r937
http://evolt.org /article/TopTenSQL/18/131/evolt.org

Mine's a little older and does not discuss SELECT TOP.

For More Information


This was first published in May 2001

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.