问题
I have searched others' code and tried to customize in my case, but it seemed when the question was the "max", it worked. When it comes to find the top 100, it was not working. I am trying to get the first 100 people hired in the firm. I first tried TOP(100) and then RANK(), I guess they would both work. I was not super familiar with the syntax though. I wonder would anyone could kindly provide me with any suggestion on my code?
Thank you very much!
SELECT d.department_name, d.department_id, e.first_name, e.hire_date, e.salary
from Dtable_department d join
Etable_employee e
on e.department_id = d.department_id
where hire_date = (select DENSE_RANK() OVER (PARTITION BY e.hire_date ORDER BY hire_date DESC) AS E_RANK_hire WHERE rownum=100))
Group BY E_RANK_hire
order by E_RANK_hire
回答1:
To get the first 100 people hired in the firm
First of all, Be careful about the tie cases are included within the results of both queries below. e.g. even if you have employee with equal hire date, they're included in the lists, meaning lists have at least 100 people.
If your Database version is 12c-
, then you need to use a subquery in which to return the result of dense_rank()
function :
select department_name, department_id, first_name, hire_date, salary
from
(
select d.department_name, d.department_id, e.first_name, e.hire_date, e.salary,
dense_rank() over ( order by hire_date ) as e_rank_hire
from Dtable_department d
join Etable_employee e
on e.department_id = d.department_id
)
where e_rank_hire <= 100
order by e_rank_hire;
If your Database version is 12c+
, then you do not need to use a subquery by the sake of fetch
clause :
select d.department_name, d.department_id, e.first_name, e.hire_date, e.salary
from Dtable_department d
join Etable_employee e
on e.department_id = d.department_id
order by hire_date
fetch first 100 rows with ties;
Pay attention for your case that using partition by
clause is wrong and should be removed within the dense_rank()
function's expression, and order of hire dates shouldn't be descending but ascending.
Demo for Top 10 Employee
来源:https://stackoverflow.com/questions/57021295/use-top-or-rank-when-finding-the-first-few-or-the-most-observations