views:

39

answers:

1

Using Sql-Server 2005.

I have Users table with 3 columns. userID, parentUserID and userEmail. Top level users have null in parentUserID, child users have some userID. I want to write a query that counts children up to lowest level of certain userID.

Select user with all his children, their children .... so on. I just need count of those users below top level user. I don't need details or their userID.

thanks

+2  A: 
DECLARE @TargetUserId int
SET @TargetUserId = 1;

WITH  Children AS

(
SELECT users.userID, users.parentUserID 
FROM users 
WHERE parentUserID =  @TargetUserId 
UNION ALL
SELECT users.userID, users.parentUserID 
FROM users 
 JOIN Children ON  users.parentUserID = Children.userID
)

SELECT COUNT(*) As SubordinateCount FROM Children
Martin Smith
You need a -1 in there somewhere, so that the target user is not counted as one of its children.
Philip Kelley
@Philip - No. The top level is `parentUserID = @TargetUserId ` not `UserID = @TargetUserId ` so the target user is never brought in.
Martin Smith
@Martin Smith, thanks
eugeneK
@eugeneK I was missing a semi colon before the CTE which I have now edited in.
Martin Smith