Click here to Skip to main content
15,908,437 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Need to Pass employee Id and get total number of employees working under the manager whose employee id is passed in SQL.

Out should be like this : -

EmplD NoofEmployees

1234 10
2562 25

Where 10 & 25 is actually the total number of employees working under the manager of EmplD 1234 and 2562 resp.

What I have tried:

I tried CTE and Self Join but i need a solution with better performance.
Posted
Updated 3-May-17 0:32am
v2

1 solution

So, you want us to give you a query to work with data that we can't see, and have no idea how it is organised?

That might not be easy, but...
Assuming your data is similar to this:
Employees: ID   Name   ManagerID
Then a simple GROUP BY will do it:
SQL
SELECT ManagerID, COUNT(ID) FROM Employees GROUP BY ManagerID
If it isn't, we'd need a load more info before we could begin to answer.

"The Table is something like this :"

Use a JOIN with the GROUP by:
SQL
SELECT e.ID, e.Name, m.MngCount FROM EMPLOYEE e
JOIN (SELECT ManagerID, COUNT(ID) as MngCount FROM Employees GROUP BY ManagerID) m 
ON e.ManagerID = m.ManagerID
 
Share this answer
 
v2
Comments
Deepak.xip 3-May-17 6:41am    
Hi OriginalGriff,
The Table is something like this :
ID Name ManagerID
1234 xyz 526
2567 abc 552
5241 lmn 526
4141 ycg 526
7485 asf 552

Now, I need to write a query (keeping in mind minimum execution time as the table has around 70 lakh records) so that the output should be like this :

ID Name EmployeeCount(No. of employees working under each employees' manager)
1234 xyz 3
2567 abc 2
5241 lmn 3
4141 ycg 3
7485 asf 2
OriginalGriff 3-May-17 7:20am    
Answer updated

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900