11.3 递归查找引用,直到指定值

 

根据某公司组织结构表,查询北京分公司的下属机构,并列出其上级机构名称,多层的用逗号分隔。部分数据如下:

ID ORG_NAME PARENT_ID
1 Head Office 0
2 Beijing Branch Office 1
3 Shanghai Branch Office 1
4 Chengdu Branch Office 1
5 Beijing R&D Center 2

每个机构在递归查找上级机构时,如果查找到指定值(例如北京分公司)则停止递归并保留当前机构,查找不到的机构则过滤掉。使用 A.prior(F,r) 递归查找引用直到指定记录 r。

脚本:

A
1 =T(“Organization.txt”)
2 >A1.switch(PARENT_ID,A1:ID)
3 =A1.select@1(ORG_NAME==“Beijing Branch Office”)
4 =A1.new(ID,ORG_NAME,~.prior(PARENT_ID,A3) :PARENT_NAME)
5 =A4.select(PARENT_NAME!=null)
6 =A5.run(PARENT_NAME=PARENT_NAME.(PARENT_ID.ORG_NAME).concat@c())

A1:导入组织机构表。
A2:将父机构 ID 外键对象化,转换为相应的父机构记录,实现外键对象化。
A3:选出北京分公司的记录。
A4:创建由序号、部门名称和所有上级部门的记录集合组成的表。
A5:选出父机构不为空的记录,即北京分公司的记录。
A6:循环将父机构名称拼成由逗号分隔的字符串。

运行结果:

A4:

imagepng

A5:

ID ORG_NAME PARENT
2 Beijing Branch Office []
5 Beijing R&D Center [[5,Beijing R&D Center,]]
6 Beijing Marketing Department [[5,Beijing Marketing Department,]]
7 Beijing AI R&D Department [[7,Beijing AI R&D Department,],[5,Beijing Marketing Department,]]
8 Beijing Internet R&D Department [[8, Beijing Internet R&D Department,],[5,Beijing R&D Center,]]
9

A6:

ID ORG_NAME PARENT
2 Beijing Branch Office
5 Beijing R&D Center Beijing Branch Office
6 Beijing Marketing Department Beijing Branch Office
7 Beijing AI R&D Department Beijing R&D Center,Beijing Branch Office
8 Beijing Internet R&D Department Beijing R&D Center,Beijing Branch Office
9 Beijing Internet Interface R&D department Beijing Internet R&D Department,Beijing R&D Center,Beijing Branch Office
10 Beijing Market Research Team Beijing Marketing Department,Beijing Branch Office