我正在尝试获取此查询的层次结构级别。这是CTE递归查询
WITH CategoryRec AS
(
SELECT Id, Parentid, Name
FROM dbo.Category
UNION ALL
SELECT cr.Id, c.Parentid, cr.Name
FROM CategoryRec AS cr INNER JOIN dbo.Category AS c ON cr.Parentid = c.Id
WHERE c.Parentid IS NOT NULL
)
SELECT DISTINCT Id, Parentid, Name
FROM CategoryRec
此问题与此问题有关:How to get the full Hierarchy with SQL CTE
感谢您的帮助
答案 0 :(得分:2)
您需要添加一个名为Level
的列(或任何您想要调用的列) - 两者都是“锚点”SELECT以及CTE的递归部分 - 如下所示:
WITH CategoryRec AS
(
SELECT Id, Parentid, Name, 1 AS 'Level'
FROM dbo.Category
UNION ALL
SELECT cr.Id, c.Parentid, cr.Name, cr.Level + 1
FROM CategoryRec AS cr
INNER JOIN dbo.Category AS c ON cr.Parentid = c.Id
WHERE c.Parentid IS NOT NULL
)
SELECT DISTINCT Id, Parentid, Name, Level
FROM CategoryRec
答案 1 :(得分:2)
您需要在第一个查询中选择层次结构的顶级,级别为marc_s。
;WITH CategoryRec AS
(
SELECT a.Id,
a.Parentid,
a.Name,
1 AS 'Level'
FROM dbo.Category as a
WHERE a.Parentid IS NULL
UNION ALL
SELECT b.Id,
b.Parentid,
b.Name,
a.Level + 1
FROM CategoryRec as a
INNER JOIN
dbo.Category as b on b.Parentid = a.Id
WHERE b.Parentid IS NOT NULL
)
SELECT Id, Parentid, Name, Level
FROM CategoryRec
答案 2 :(得分:0)
返回正确的级别。但不确定这个查询是否符合性能应该是
WITH CategoryRec AS
(
SELECT Id, Parentid, Name, 1 as [Level]
FROM dbo.Category
where Parentid IS NULL
UNION ALL
SELECT c.Id, c.Parentid, c.Name, (cr.[Level] + 1) as [Level]
FROM Category c INNER JOIN
CategoryRec AS cr ON c.Parentid = cr.Id
),
CategoryRec2 as
(
SELECT Id, Parentid, Name, [Level]
FROM CategoryRec
UNION ALL
SELECT cr.Id, c.Parentid, cr.Name, cr.[Level]
FROM CategoryRec2 AS cr INNER JOIN
CategoryRec AS c ON cr.Parentid = c.Id
WHERE c.Parentid IS NOT NULL
)
SELECT Id, Parentid, Name, [Level]
FROM CategoryRec2