如何根据原表的部门id查找下一级部门

炎同学要努力 2023-06-15 08:59:57

如何根据原表的顶级部门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

...全文
158 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
CSDN-Ada助手 2023-06-15
精选
  • 打赏
  • 举报
回复
您的问题已经帮您同步至问答, 链接: https://ask.csdn.net/questions/7964571, 请您保持关注, 如果回答有帮助解决此问题, 麻烦您动动小手给相关的回答点赞, Ada会在评论区为您更新结题状态
炎同学要努力 2023-06-15
  • 打赏
  • 举报
回复

;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

幸福感奇差 2023-06-15
  • 打赏
  • 举报
回复

select t1.*
from table t1, table t2 -- 全连接
where len(t1.id) = len(t2.id) - 2 -- 只查它下一级部门
and charindex(t1.id, t2.id) = 1 -- 是前缀

幸福感奇差 2023-06-15
  • 打赏
  • 举报
回复

给个表样吧,问题略模糊

炎同学要努力 2023-06-15
  • 举报
回复
@幸福感奇差 给了

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧