Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Cumulative count

Author  Topic 

flyrplnz
Starting Member

6 Posts

Posted - 2006-04-06 : 17:11:20
I have an employee table which houses all employees and the employee to manager relationship. Such as the following.

EmployeeId
FirstName
LastName
ManagerId
IsManager

Contained is about four levels of employees that report to managers on up to the top dog . A subordinate of a manager would have the manager's EmployeeId value in their ManagerId column.

How do I run a query to count the total number of employees each level of management have, not just their direct reports but including all indirect reports as well? In other words the top dog's count should include every record in the table including his own (because I need to know how many folks are on the team).

I'm stumped

AjarnMark
SQL Slashing Gunting Master

3246 Posts

Posted - 2006-04-06 : 17:22:48
The best approach depends on the version of SQL Server you are running. If you have SQL 2005, you can use Recursive Common Table Expressions, otherwise you'll need some more elaborate code. You might want to search here on trees and hierarchies. Or this article might help.

---------------------------
EmeraldCityDomains.com
Go to Top of Page

flyrplnz
Starting Member

6 Posts

Posted - 2006-04-06 : 17:35:09
Not on 2005 yet. Guess its the hard way.

However I forgot to mention another column which is called Leaf which contains a hierarchical number that helps determine a managers direct reports. It would look something like this:

Bob is a manager and he is the top dog. His Leaf value is 00001
Sally reports to Bob and her Leaf value is 00001.00001
Jerry also reports to Bob and his Leaf value is 00001.00002
Jerry has a direct report named Mike and his Leaf value is 00001.00002.00001
See how it works?

I tried to figure a way to utilize the Leaf column but it got more confusing in my head.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-04-07 : 01:39:10
Also refer this
http://www.nigelrivett.net/RetrieveTreeHierarchy.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -