34,837
社区成员




如何根据原表的顶级部门id查找它包含的下一级部门
顶级部门的id长度有(4,6,8)位,下一级部门有(6,8,10)位
顶级部门表:
id name
00 A
01 B
部门信息表
id name
0001 cc1
0002 cc2
0013 cc3
0101 kk1
0103 kk2
;with t1 as
(
select id = '00' ,name = 'A'union all
select id = '01' ,name = 'B'union all
select id = '001' ,name = 'C'
)
,t2 as
(
select id = '0001' ,name = 'cc1'union all
select id = '0002' ,name = 'cc2'union all
select id = '0013' ,name = 'cc3'union all
select id = '0101' ,name = 'kk1'union all
select id = '0102' ,name = 'kk2'union all
select id = '00101' ,name = 'ww1'union all
select id = '00102' ,name = 'ww2'
)
,t3 as
(
select t1.id,t1.name,t2.id as 下一级id,t2.name as 下一级name
from t1, t2
where t2.id like t1.id + '__'
)
,t4 as
(
select id,count(*)as 数量
from t3
group by id
)
select t3.id,t3.name,t4.数量 as 下一级数量,t3.下一级id,t3.下一级name
from t3 left join t4 on t3.id =t4.id
select t1.*
from table t1, table t2 -- 全连接
where len(t1.id) = len(t2.id) - 2 -- 只查它下一级部门
and charindex(t1.id, t2.id) = 1 -- 是前缀