如何使用 parentId 查找 Child 的计数

How to find count of Child using parentId

如何计算每一行中 children 的个数?

例如:

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

等等。在下一栏中

您可以使用递归 CTE 来完成此操作,但应该使用简单连接来完成。首先求出每个节点的个数,不包括没有父节点的节点:

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

如果没问题,就加入初始table:

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];

这应该没问题,当ROW COUNT=0

时你需要isnull()函数
 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