【发布时间】:2020-08-12 05:54:20
【问题描述】:
我有一张包含单位地理结构的表格。有父子关系列,但我想使用现有的文本字段(而不是递归)来查找项目之间的关系级别。
(这里是一个建表脚本)
drop table if exists #temp_structure
create table #temp_structure
(org_id int,
parent_org_id int,
org_name nvarchar(255),
search_tree nvarchar(255))
insert into #temp_structure
values
(1,null,'World','| 1 |'),
(2,1,'Europe','| 1 | 2 |'),
(3,1,'North America','| 1 | 3 |'),
(4,1,'South America','| 1 | 4 |'),
(5,1,'Asia','| 1 | 5 |'),
(6,1,'Africa','| 1 | 6 |'),
(7,1,'Australia','| 1 | 7 |'),
(8,2,'Spain','| 1 | 2 | 8 |'),
(9,2,'Germany','| 1 | 2 | 9 |'),
(10,2,'Italy','| 1 | 2 | 10 |'),
(11,2,'France','| 1 | 2 | 11 |'),
(12,8,'Madrid ','| 1 | 2 | 8 | 12 |'),
(13,8,'Barcelona ','| 1 | 2 | 8 | 13 |'),
(14,9,'Berlin','| 1 | 2 | 9 | 14 |'),
(15,9,'Munich','| 1 | 2 | 9 | 15 |'),
(16,10,'Rome','| 1 | 2 | 10 | 16 |'),
(17,10,'Milano','| 1 | 2 | 10 | 17 |'),
(18,11,'Paris','| 1 | 2 | 11 | 18 |'),
(19,11,'Marseille','| 1 | 2 | 11 | 19 |')
我想要达到的预期结果如下所示(我只列出了一个 4 级示例):
+--------+-------------+------------+
| org_id | search_item | nest_level |
+--------+-------------+------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 2 | 1 | 2 |
| 3 | 3 | 1 |
| 3 | 1 | 2 |
| 4 | 4 | 1 |
| 4 | 1 | 2 |
| 5 | 5 | 1 |
| 5 | 1 | 2 |
| 6 | 6 | 1 |
| 6 | 1 | 2 |
| 7 | 7 | 1 |
| 7 | 1 | 2 |
| 8 | 8 | 1 |
| 8 | 2 | 2 |
| 8 | 1 | 3 |
| 9 | 9 | 1 |
| 9 | 2 | 2 |
| 9 | 1 | 3 |
| 10 | 10 | 1 |
| 10 | 2 | 2 |
| 10 | 1 | 3 |
| 11 | 11 | 1 |
| 11 | 2 | 2 |
| 11 | 1 | 3 |
| 12 | 12 | 1 |
| 12 | 8 | 2 |
| 12 | 2 | 3 |
| 12 | 1 | 4 |
.....................................
+--------+-------------+------------+
我能够使用 STRING_SPLIT 提取 org_id-search_item 关系,但我仍然错过了棘手的级别部分(我想知道枚举 '|' 字符)
SELECT t.org_id
--,substring(replace(search_tree, ' ', ''), 2, len(replace(search_tree, ' ', '')) - 2)
,ss.value as search_item
FROM #temp_structure t
CROSS APPLY string_split(substring(replace(search_tree, ' ', ''), 2, len(replace(search_tree, ' ', '')) - 2),'|') ss
【问题讨论】:
-
这是两个独立的操作。首先,您需要递归 CTE 来计算级别。其次,将 search_tree 拆分(使用像Jeff Moden'sDelimittedSplitN4k 这样的顺序保留拆分器)到一个表中,其中 fk 引用回 org_id 或嵌套的 JSON(或 XML)。
标签: sql sql-server split