Skip to content
Advertisement

How to find a destinct values in a table that are larger than all values that reference it?

I need to find the names of bosses who were hired after all the hired date of all their subordinates. Here is what I have got so far:

SELECT DISTINCT 
    TRIM(boss.first_name || ' ' || boss.last_name) AS NAME,
    boss.phone_number AS phone
FROM
    HR.employees e
    INNER JOIN HR.employees boss ON (boss.employee_id = e.manager_id)
WHERE
    boss.hire_date > MIN(e.hire_date)
    AND boss.hire_date > MAX(e.hire_date);

The idea was to check that the boss.hire_date is larger than the earliest and latest hire_date of his subordinates.

However I get following error message:

ORA-00934: group function is not allowed here

Any idea how I have to restructure the query?

Advertisement

Answer

This should work better

SELECT TRIM(boss.first_name || ' ' || boss.last_name) AS NAME,
     boss.phone_number AS phone
FROM HR.employees boss 
INNER JOIN
(   
SELECT e.manager_id, MAX(e.hire_date) AS Max_hire_date
FROM  HR.employees e
GROUP BY e.manager_id
) m ON m.manager_id=boss.employee_id
WHERE boss.hire_date > m.Max_hire_date

Note that I have supposed that a boss can’t manage itself. In an usual hierarchical database, the top manager has its manager_id field = NULL. If in your data a boss can have its manager_id =i ts own employee_id, it wont work.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement