开发者

Counting a root's children in SQL

开发者 https://www.devze.com 2023-04-10 02:10 出处:网络
Let\'s say I have a table with 3 columns: item ID \'ID\' parent ID \'ParentID\' item name \'Title\' 开发者_运维知识库

Let's say I have a table with 3 columns:

  1. item ID 'ID'
  2. parent ID 'ParentID'
  3. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消