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