【发布时间】:2018-11-08 21:03:39
【问题描述】:
我正在尝试创建一个查询以将分层表结构转换为列。
每个节点都有一个父节点。但是 Node 不是唯一的编号。在每个根叶中,它都是独一无二的。但可以存在于另一个父级之下。
我尝试使用 CTE。并带有多个 SELECT .. UNION ...
但我无法过滤掉它在同一个根叶中。 例如,我将父 01 的两条选定行都设为 09。
最大深度为 4。
而我想要的结果是。 RUBRICCODE;NAME0;NAME1;NAME2;NAME3;NAME4 0100000000;金融管理文件;;;; 0100100000;金融管理文件;Patientenadministratie;;; ...
select * from (
select t0.RUBRICCODE, t0.PATH, t0.NAME Rubr0, '' Rubr1, '' Rubr2, '' Rubr3, '' Rubr4
from dacs_treestructure t0
where t0.DEPTH = 0
UNION ALL
select t1.RUBRICCODE, t1.PATH, t0.NAME Rubr0, t1.NAME Rubr1, '' Rubr2, '' Rubr3, '' Rubr4
from dacs_treestructure t0
join dacs_treestructure t1 on t0.NODE = t1.PARENT
where t0.DEPTH = 0 and t1.DEPTH = 1
UNION ALL
select t2.RUBRICCODE, t2.PATH, t0.NAME Rubr0, t1.NAME Rubr1, t2.NAME Rubr2, '' Rubr3, '' Rubr4
from dacs_treestructure t0
join dacs_treestructure t1 on t0.NODE = t1.PARENT
join dacs_treestructure t2 on t1.NODE = t2.PARENT
where t0.DEPTH = 0 and t1.DEPTH = 1 and t2.DEPTH = 2
) x order by 1
查询结果。所选行来自父 09。不应存在。
【问题讨论】:
-
样本数据最好使用DDL + DML。请edit您的问题包括它,您当前的尝试和您想要的结果。更多详情,read this.
-
请不要将解决方案作为问题的一部分发布。将其作为您自己问题的答案发布,并在时间限制结束后接受。
-
抱歉,我查看了按钮。更改它,并单独添加。
标签: sql sql-server tsql hierarchical-data