Counting a root's children in SQL
Let's say I have a table with 3 columns:
- item ID 'ID'
- parent ID 'ParentID'
- item name 'Title'
Now, how should I count how many children a Root has?
SELECT COUNT(*)
FROM T
WHERE ParentID = @ParentID
If you want descendants not just immediate children you would need a recursive CTE.
;WITH R AS
(
SELECT ID
FROM T
WHERE ParentID = @RootID
UNION ALL
SELECT T.ID
FROM T
JOIN R ON R.ID = T.ParentID
)
SELECT COUNT(*)
FROM R
精彩评论