I have a emp table as follows:
userID varchar(10)
ManagerID varchar(10)
Data:
UserID ManagerID
101 102
103 102
104 103
I need to find all the users under a manager directly or indirectly.
The output should be as follows:
If it is for 102:
Manager ReportingUsers
--------------------------
102 101,103
And if we check for 104 the output should be:
Manager ReportingUsers
--------------------------
104 102,101,103 `
The query I am writing for achieving this is as follows
SELECT managerID, GROUP_CONCAT(userID) FROM emp GROUP BY managerID;
But the output I get satisfies the first output but not the second:
+-----------+----------------------+
| MANAGERID | GROUP_CONCAT(USERID) |
+-----------+----------------------+
| 102 | 101,103 |
| 104 | 102 |
+-----------+----------------------+
How do I achieve this use case using Cursors and Stored Procedures through which I can get the output for every manager?
Just an update If I use the below query I get the result for my second example as well but the first example for 102 does not get satisfied:
SELECT m.MANAGERID, GROUP_CONCAT(m.USERID,';',(Select Group_Concat(n.USERID) from emp as n where m.userID=n.managerID or n.managerID=NULL group by n.managerID)) as ReportingUsers FROM emp as m GROUP BY managerID;
If I can get a solution using cursors and procedures that would also work.