有孩子的用户数

时间:2014-04-13 12:39:44

标签: sql sql-server

我有一张这样的表:

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

所以输出应该是这样的:

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

所以请帮助,如果有任何混淆,请告诉我?

2 个答案:

答案 0 :(得分:3)

试试这个

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

答案 1 :(得分:0)

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