Use TOP or Rank when finding the first few or the most observations

痞子三分冷 提交于 2019-12-11 05:35:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!