I have one table called 'employees' with some data like employee id, employee name and manager id. I have self joined it to show the number of subordinates under each manager.
It looks like this and it works fine: SQL fiddle link
The table looks like this:
CREATE TABLE employees (
emp_id INT,
emp_name VARCHAR(16),
mgr_id INT,
);
INSERT INTO employees VALUES
(1,'George',5),
(2,'Monica',5),
(3,'Rachel',5),
(4,'Marie',5),
(5,'Emma',6),
(6,'David',NULL);
And the query itself that shows the number of direct subordinates grouped by manager is this:
SELECT
m.emp_name,
COUNT(e.emp_name) AS number_of_subordinates
FROM
employees as e
JOIN employees as m
ON e.mgr_id=m.emp_id
GROUP BY m.emp_name
ORDER BY number_of_subordinates DESC
However, this shows me the direct subordinates of each manager. What I want to be able to show as well is the number of indirect subordinates. So, for example, whilst Emma would still have 4 subordinates, David would have the 4 Emma has plus Emma which equals 5 (since he's Emma's boss and Emma is the boss of George, Monica, Rachel and Marie.