递归计算后代数量
我有一个带有导航的表格,可以使用 ParentId 自行连接。我正在尝试计算每个记录有多少个后代,我知道我需要在递归中增加一个计数器,我只是不知道如何去做!
任何帮助将不胜感激!
CREATE TABLE [dbo].[Navigation](
[Id] [int] IDENTITY(1,1) NOT NULL,
[AnchorText] [varchar](50) NOT NULL,
[ParentID] [int] NULL)
insert into Navigation
select 'Level 1', null
union
select 'Level 2', 1
union
select 'Level 3', 2
union
select 'Level 4', 3
WITH NavigationCTE (Id, AnchorText, ParentId, NumberofDescendants) as
(
Select Id, AnchorText, ParentId, 'Number of Descendants Here' as NumberofDescendants
from dbo.Navigation nav
union ALL
select nav.Id, nav.AnchorText, nav.ParentId, 'Number of Descendants Here' as NumberofDescendants
from dbo.Navigation nav
join Navigation ON nav.ParentId = nav.Id
)
SELECT * FROM NavigationCTE
编辑添加级别并增加递归:
WITH NavigationCTE (Id, AnchorText, ParentId, Level) as
(
Select nav.Id, nav.AnchorText, nav.ParentId, 0 as Level
from dbo.Navigation AS nav
UNION ALL
select nav.Id, nav.AnchorText, nav.ParentId, Level + 1
from dbo.Navigation AS nav
join Navigation AS nav2 ON nav.ParentId = nav2.Id
)
SELECT * FROM NavigationCTE
I have a table with navigation that joins back on its self using ParentId. I am trying to calculate how many descendents each record has, I know that I need to increment a counter in the recursion, I'm just not sure how to go about it!
Any help would be greatly appreciated!
CREATE TABLE [dbo].[Navigation](
[Id] [int] IDENTITY(1,1) NOT NULL,
[AnchorText] [varchar](50) NOT NULL,
[ParentID] [int] NULL)
insert into Navigation
select 'Level 1', null
union
select 'Level 2', 1
union
select 'Level 3', 2
union
select 'Level 4', 3
WITH NavigationCTE (Id, AnchorText, ParentId, NumberofDescendants) as
(
Select Id, AnchorText, ParentId, 'Number of Descendants Here' as NumberofDescendants
from dbo.Navigation nav
union ALL
select nav.Id, nav.AnchorText, nav.ParentId, 'Number of Descendants Here' as NumberofDescendants
from dbo.Navigation nav
join Navigation ON nav.ParentId = nav.Id
)
SELECT * FROM NavigationCTE
EDIT Added Level and Incremented in recursion:
WITH NavigationCTE (Id, AnchorText, ParentId, Level) as
(
Select nav.Id, nav.AnchorText, nav.ParentId, 0 as Level
from dbo.Navigation AS nav
UNION ALL
select nav.Id, nav.AnchorText, nav.ParentId, Level + 1
from dbo.Navigation AS nav
join Navigation AS nav2 ON nav.ParentId = nav2.Id
)
SELECT * FROM NavigationCTE
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通用表表达式提供了您需要的递归功能。研究本文示例查询中 Level 字段的创建和使用。它执行的增量正是您想要实现的类型,在锚查询中从 0 开始。
基于提供的示例的工作查询:
Common Table Expressions provide the kind of recursive functionality you need. Study the creation and use of the Level field in the article's sample query. It performs exactly the kind of incrementing you want to achieve, starting with 0 in the anchor query.
Working query based on provided sample: