如何使用parentId

时间:2019-02-04 07:51:59

标签: sql-server tsql hierarchy

enter image description here

如何找到每一行的孩子人数?

例如:

   1 ROW COUNT=1
   2 ROW COUNT=0 
   ...

,依此类推。在下一列

2 个答案:

答案 0 :(得分:1)

应该没问题,当isnull()时需要ROW COUNT=0函数

 SELECT 
        PA.ID, 
        PA.Title_Name, 
        ISNULL(P.COUNTT,0) CountOfID 
 FROM #My_Table PA
 LEFT JOIN (
             SELECT COUNT(*) COUNTT, Parent_ID from #My_Table GROUP BY Parent_ID
             ) as P on P.Parent_ID = PA.ID

答案 1 :(得分:0)

您可以使用递归CTE来做到这一点,但是应该通过简单的连接来完成。首先,找到每个节点的数量,不包括没有父节点的节点:

SELECT [ParentID] 
      ,COUNT(*)
FROM MyTable 
WHERE [ParentID] <> 0
GROUP BY [ParentID];

如果可以,只需加入初始表即可

SELECT *
FROM MyTable T1
LEFT JOIN
(
    SELECT [ParentID] 
          ,COUNT(*) AS [all_childs]
    FROM MyTable 
    WHERE [ParentID] <> 0
    GROUP BY [ParentID]
) T2
    oN T1.[parentID] = T2.[ParentID];