Answer the question
In order to leave comments, you need to log in
How to count the number of nodes in a SQL tree?
The question is taken from here:
https://stackoverflow.com/questions/49636142/how-t...
There is a table tree. You need to count the number of nodes in the tree.
The table creation code and the recursive query itself to collect nodes:
INSERT INTO Organization_structure VALUES
(100, NULL),
(129, 100),
(134, 100),
(439, 129),
(450, 129),
(133, 134),
(133, 134),
(501, 439),
(602, 501);
with tree as
(
select orgId, parentId,0 as tree_order, path = cast('root' as varchar(100))
from Organization_structure
where parentID is null
union all
select os.orgId, os.parentId, 1 + tree_order as tree_order,
path = cast(tree.path + '/' + right(('000000000' + os.orgId), 10) as varchar(100))
from Organization_structure os
join tree
on tree.orgId = os.parentId
)
select orgId, tree_order, path, t2.cnt
from tree
cross apply (select count(*) cnt from tree t1 where t1.path like tree.path + '%') t2
order by tree_order;
root/134/133
Answer the question
In order to leave comments, you need to log in
I want to display count of children for every node in the tree.Subsidiaries , not all ! All the above solutions are incorrect because the node itself is also considered.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question