您当前的位置: 首页 >  sql

潇洒白羊

暂无认证

  • 2浏览

    0关注

    68博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

sql server递归查询

潇洒白羊 发布时间:2022-06-12 17:37:17 ,浏览量:2

如下图,查询每个节点之间的关系,以及层级 请添加图片描述表中存储的数据如下: 在这里插入图片描述 数据类型: 在这里插入图片描述

1、查询每个节点之间的关系,以及层级

逻辑: 该表自连接,son_id 与 father_id 相等,一步一步连接下去

WITH cte(son_id, father_id, ReportPath, Level) AS
(
    SELECT son_id, father_id, CAST(son_id + '->' + father_id AS NVARCHAR(max)) AS ReportPath,2 AS Level FROM test where father_id = 0
    UNION ALL
    SELECT c.son_id, c.father_id, c.son_id+ '->'+ P.ReportPath AS ReportPath , p.Level+1 AS Level
    FROM cte P INNER JOIN test c ON P.son_id = c.father_id
    
)
SELECT *  FROM cte ORDER BY son_id;

在这里插入图片描述

2、不限制 where father_id = 0 这个起始条件

则会出现每一层的关系,然后用son_id,father_id 分组后取最大的层级即可

WITH cte(son_id, father_id, ReportPath, Level) AS
(
    SELECT son_id, father_id, CAST(son_id + '->' + father_id AS NVARCHAR(max)) AS ReportPath,2 AS Level FROM test 
    UNION ALL
    SELECT c.son_id, c.father_id, c.son_id+ '->'+ P.ReportPath AS ReportPath , p.Level+1 AS Level
    FROM cte P INNER JOIN test c ON P.son_id = c.father_id
    
)
SELECT * into test_tree FROM cte ORDER BY son_id;

在这里插入图片描述

select * from (
select * ,DENSE_RANK( )over(partition by son_id,father_id order by Level desc) as rn from test_tree)t
where rn =1

排序后获取结果与有限制条件的结果一致。

关注
打赏
1655040589
查看更多评论
立即登录/注册

微信扫码登录

0.0422s