Self -Join
SELECT e.last_name, e.employee_id, m.last_name as manager, e.manager_id, m.last_name,m.employee_id
FROM
hr.employees e, hr.employees m
WHERE e.manager_id = m.employee_id
order by m.employee_id DESC
And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:
inner join
SELECT e.last_name, e.employee_id, NVL(m.last_name,'No Manager') as manager, e.manager_id, m.last_name,m.employee_id
FROM
hr.employees e, hr.employees m
WHERE e.manager_id = m.employee_id (+)
order by m.employee_id DESC
ANSI SQL
SELECT e.last_name, e.employee_id, m.last_name as manager, e.manager_id, m.last_name,m.employee_id
FROM
hr.employees e LEFT OUTER JOIN hr.employees m
on e.manager_id = m.employee_id
order by m.employee_id DESC
SELECT
sup.employee_id,
sup.first_name,
sup.last_name,
COUNT (sub.employee_id) AS number_of_employees
FROM hr.employees sub
JOIN hr.employees sup
ON sub.manager_id = sup.employee_id
GROUP BY sup.employee_id, sup.first_name, sup.last_name;
SELECT
sub.employee_id AS subordinate_id,
sub.first_name AS subordinate_first_name,
sub.last_name AS subordinate_last_name,
sup.employee_id AS superior_id,
sup.first_name AS superior_first_name,
sup.last_name AS superior_last_name
FROM hr.employees sub
JOIN hr.employees sup
ON sub.manager_id = sup.employee_id
ORDER BY superior_id;
No comments:
Post a Comment