我有一个表结构如下:
表:
Parent branchname branchlevel level**
tree a 1.1 1
tree b 1.2 1
tree c 1.3 1
tree d 1.4 1
tree e 1.10 1
b f 1.1 2
b g 1.2 2
b h 1.3 2
我需要一个如下所示的结果集:
tree 1
a 1.1
e 1.10
b 1.2
f 1.2.1
g 1.2.2
h 1.2.3
c 1.3
d 1.4
到目前为止我的SQL:
select *
from ((select distinct parent,'1' as branchlevel
from tree
where parent not in(select branchname from tree))
union all (select branchname,branchlevel
from tree
where (cast(level as int))<(select max(CAST(level as int)) from tree))
union all (select b.branchname,(SUBSTRING(b.branchlevel,1,2)+b.level+'.'+SUBSTRING(b.branchlevel,3,2))branchlevel
from tree a
inner join tree b on a.branchname=b.parent
where (cast(a.level as int))<(select max(CAST(level as int)) from tree)))a
order by branchlevel
答案 0 :(得分:0)
您可以使用递归CTE来获得所需的输出:
;WITH TreeRoot AS
(
SELECT rootName = (SELECT TOP 1 Parent
FROM #Tree
WHERE Parent NOT IN (SELECT branchname FROM #Tree))
),
TreeLevels AS (
-- Recursive CTE Anchor member is simply: (tree, NULL, 0, 1)
SELECT (SELECT rootName FROM TreeRoot) AS NodeName,
CAST(NULL AS VARCHAR(10)) AS ParentName,
0 AS level,
CAST('1' AS VARCHAR(10)) AS branchlevel
UNION ALL
SELECT branchname AS NodeName,
t.Parent AS ParentName,
tl.level + 1 AS level,
CAST(CONCAT(tl.branchlevel,
'.',
SUBSTRING(t.branchlevel, CHARINDEX('.', t.branchlevel)+1, LEN(t.branchlevel) - CHARINDEX('.', t.branchlevel))) AS VARCHAR(10)) AS branchlevel
FROM #Tree AS t
INNER JOIN TreeLevels AS tl ON t.Parent = tl.NodeName
)
SELECT NodeName, branchlevel
FROM TreeLevels
ORDER BY branchlevel
SUBSTRING
函数用于从branchlevel字段中获取最后一个数字,即得到&#39; 2&#39;出于&#39; 1.2&#39;。 CONCAT
用于递归地将此数字添加到任何先前获得的分支级别数。
即使分支级别超过2,此查询也会起作用。SQL Fiddle Demo