Utilisateurs avec leur nombre d'enfants

J'ai une table comme celle-ci:

Userid Name ParentId 1 A Null 2 B 1 3 C 1 4 D 2 5 E 3 

donc la sortie devrait être comme ceci:

 UserId Name Childs 1 A 2 // A has two children B and C 2 B 1 // B has one child D 3 C 1 // C has one child E 

Alors s'il vous plaît aider et laissez-moi savoir si une confusion?

Essaye ça

 SELECT t1.UserId, t1.Name, count(t2.UserId) FROM table t1 INNER JOIN table t2 ON t2.parentid = t1.UserId GROUP BY t1.UserId, t1.Name 
 DECLARE @test Table (ID INT, Name VARCHAR(20),CID INT) INSERT INTO @test VALUES (1, 'A',NULL), (2, 'B',1), (3, 'C' ,1), (1, 'D',2), (2, 'E',3); ;WITH CTE AS ( select ID,Name from @test ) select c.ID,c.Name,COUNT(t.ID) from CTE C INNER JOIN @test t ON t.CID = c.ID GROUP by c.ID,c.Name