The easiest approach is generally to use an analytic function here. The wrinkle, though, comes if there are ties. If there are two people in the same department that were hired on the same day, which isn't terribly unlikely, do you want to return both of them? Or do you want to specify a secondary criteria to break the tie? Or do you just want Oracle to randomly break the tie? And, if you're not looking for the top row but the top 3 or top 5, how do you treat the rows after the tie.
This query
select department_name,
employee_name,
hire_date
from (
select d.department_name,
e.first_name || ' '|| e.last_name employee_name,
e.hire_date,
row_number() over (partition by d.department_name order by e.hire_date asc) rnk
from employees e join departments d
on e.department_id=d.department_id
)
where rnk = 1
will return the employee with the earliest hire_date
in each department by randomly breaking ties if two employees were hired on the same day. If you used either the rank
or the dense_rank
function rather than row_number
, both rows would be returned. If you added an additional criteria to the order by in the analytic function, you could determine how to break the tie (for example by sorting on the employee's last name).