CTE SQL查询获取完整路径
我有一个简单的查询,
WITH conn_cte ( ParentCategoryId, CategoryId, IdsPath )
AS ( SELECT ParentCategoryId
,CategoryId
,CAST(ParentCategoryId AS varchar(1000))
FROM Ind_CategoriesConnections
WHERE ParentCategoryId = 0
UNION ALL
SELECT cc.ParentCategoryId
,cc.CategoryId
,CAST(IdsPath + ','
+ CAST (cc.ParentCategoryId AS varchar(5)) AS varchar(1000))
FROM Ind_CategoriesConnections AS cc
INNER JOIN conn_cte AS conn ON conn.CategoryId = cc.ParentCategoryId
AND cc.categoryid NOT IN (
SELECT conn.Categoryid )
)
SELECT x.*
FROM ( SELECT t.ParentCategoryId
,t.CategoryId
,t.IdsPath + ',' + CAST(t.CategoryId AS varchar(5)) AS [path]
FROM conn_cte t
INNER JOIN Ind_Categories c ON t.CategoryId = c.CategoryId
AND c.CategoryViewId = 1
AND c.IsActiveYN = 1
) x
ORDER BY x.path
我对查询(最佳)感兴趣,它只返回从根到叶的完整路径。
例如,结果为零的部分
Parent Child Path
12 16 0,8,12,16
16 17 0,8,12,16,17
17 18 0,8,12,16,17,18
17 19 0,8,12,16,17,19
是根 18,19 是叶子(和子节点),我想部分忽略像 0,8,12,16
和 0,8,12 这样的路径,16,17
并仅获取完整路径(以叶子结尾) 0,8,12,16,17,18
和 0,8,12,16,17,19
I have got simple query
WITH conn_cte ( ParentCategoryId, CategoryId, IdsPath )
AS ( SELECT ParentCategoryId
,CategoryId
,CAST(ParentCategoryId AS varchar(1000))
FROM Ind_CategoriesConnections
WHERE ParentCategoryId = 0
UNION ALL
SELECT cc.ParentCategoryId
,cc.CategoryId
,CAST(IdsPath + ','
+ CAST (cc.ParentCategoryId AS varchar(5)) AS varchar(1000))
FROM Ind_CategoriesConnections AS cc
INNER JOIN conn_cte AS conn ON conn.CategoryId = cc.ParentCategoryId
AND cc.categoryid NOT IN (
SELECT conn.Categoryid )
)
SELECT x.*
FROM ( SELECT t.ParentCategoryId
,t.CategoryId
,t.IdsPath + ',' + CAST(t.CategoryId AS varchar(5)) AS [path]
FROM conn_cte t
INNER JOIN Ind_Categories c ON t.CategoryId = c.CategoryId
AND c.CategoryViewId = 1
AND c.IsActiveYN = 1
) x
ORDER BY x.path
I am interesting in query (optimal) that only return full paths from root to leaf.
for example the part of result is
Parent Child Path
12 16 0,8,12,16
16 17 0,8,12,16,17
17 18 0,8,12,16,17,18
17 19 0,8,12,16,17,19
zero is root 18,19 are leafs (and children), I want to ignore partly paths like 0,8,12,16
and 0,8,12,16,17
and get only full paths (ended with leafs)0,8,12,16,17,18
and 0,8,12,16,17,19
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
返回
语法为 SQL Server 2008,对于 2005,更改
INSERT INTO @tbl ...
语法。Returns
The syntax is SQL Server 2008, for 2005 change the
INSERT INTO @tbl ...
syntax.你可以这样说:
You could say something like: