-3

I have a table called Employees, each employees has a salary value. I want to select the top 20 employees based on salary.

My database columns look like this:

EMPLOYEE SALARY DEPARTMENT 
--------------------------
KARTHI   500     IT
MANO     500     ADMIN
SANDY    300     HR
KARTHI   400     IT

I want to get top records like this:

EMPLOYEE SALARY DEPARTMENT 
---------------------------
KARTHI   900     IT
MANO     500     ADMIN
SANDY    300     HR

How to get top 5 records from database like above?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
PriyaRiya
  • 1
  • 7

3 Answers3

2

You can use row_number() window analytic function

select employee, salary, department 
  from
  (
   select e.*, row_number() over (order by e.salary desc) as rn
     from employees e
  ) e
 where rn <= 20;

If you have identical salaries(that's ties) for the boundary values such as the 20th-21st-22nd ranked people may have same salaries , then use :

select top 20 with ties employee, salary, department
  from employees 
 order by salary desc

to include all of the 22 people in the list. If you want to exclude 21st and 22nd people, then just use select top 20 * to ignore the ties.

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
1

use top and order by salary desc

select top 20 EMPLOYEE, sum(SALARY) as salary, DEPARTMENT from 
tablename
group by employee,department
order by 2 desc
Fahmi
  • 37,315
  • 5
  • 22
  • 31
0
SELECT DISTINCT TOP 20 E.* FROM EMP AS E ORDER BY E.SALARY DESC
Umair Rasheed
  • 436
  • 4
  • 10