gpt4 book ai didi

sql - 使用递归 CTE 遍历父/子树?

转载 作者:行者123 更新时间:2023-12-01 15:36:50 24 4
gpt4 key购买 nike

我被 cte 困住了,我想要一个查询,其中第一个父项为空。和上一个 parent 的 child ,将成为下一个 parent 的 parent ,依此类推。

WITH RESULT (PARENT,CHILD,TNAME,LEVEL)
AS
(
--anchor
SELECT E.PARENT_GENERAL_KEY,E.M_GENERAL_KEY,E.NAME ,0 AS LEVEL
FROM RPT_SYN_M_GENERAL AS E
WHERE E.PARENT_GENERAL_KEY IS NULL
UNION ALL
--outer
SELECT e.PARENT_GENERAL_KEY,E.M_GENERAL_KEY,e.NAME ,LEVEL +1
FROM RPT_SYN_M_GENERAL AS E
INNER JOIN RESULT AS D
ON E.PARENT_GENERAL_KEY=D.CHILD
)
SELECT PARENT,CHILD,TNAME,LEVEL FROM RESULT as d
order by PARENT,CHILD

以上是我的查询。请帮我遍历最后一个 child 。

我的输出是:

 PARENT CHILD   TNAME               LEVEL
NULL 0 ACCOUNT_MASTER 0
0 1 LIABILITIES 1
0 2 ASSETS 1
0 3 INCOME 1
0 4 EXPENSE 1
0 15003 POLISHED DIAMOND 1
0 15004 DEMO 1
0 15005 DEMO ( FACTORY 1
1 238 CAPITAL A/C. 2
1 1067 PROVISION 2
1 1284 SECURED LOANS 2
1 2968 UNSECURED LOANS 2
1 3535 SHARE HOLDERS 2
2 484 FIXED ASSETS A/C 2
2 3301 INVESTMENTS 2
2 4858 CURRENT ASSETS 2
2 4859 LOANS ADVANCES 2
3 867 OTHER INCOME 2
3 1246 SALES 2

我想要的输出是:

 PARENT      CHILD  TNAME             LEVEL
null 0 0
0 1 1
1 238 2
238 982 3
982 26 4
982 894 4
982 1321 4
238 7757 3
7757 7521 4

最佳答案

在没有看到您的基础表的情况下,我无法测试任何建议。但是,如果您在外部查询中切换父项和子项,看看会发生什么:

WITH RESULT (PARENT,CHILD,TNAME,LEVEL)
AS
(
--anchor
SELECT E.PARENT_GENERAL_KEY,E.M_GENERAL_KEY,E.NAME ,0 AS LEVEL
FROM RPT_SYN_M_GENERAL AS E
WHERE E.PARENT_GENERAL_KEY IS NULL
UNION ALL
--outer
SELECT D.CHILD,D.PARENT,e.NAME ,LEVEL +1 --switched parent/child
FROM RPT_SYN_M_GENERAL AS E
INNER JOIN RESULT AS D
ON E.PARENT_GENERAL_KEY=D.CHILD
WHERE LEVEL<100
)
SELECT PARENT,CHILD,TNAME,LEVEL FROM RESULT as d
order by PARENT,CHILD

关于sql - 使用递归 CTE 遍历父/子树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com