如下数据:
编码 类型 级数
001 分类 1
001001 直管 2
001001001 直管 3
002 直管 1
003 分类 1
003001 分类 2
003001001 直管 3
003001001001 直管 4现在只要取第一级直管001001 直管 2
002 直管 1
003001001 直管 3求SQL,谢谢了!
编码 类型 级数
001 分类 1
001001 直管 2
001001001 直管 3
002 直管 1
003 分类 1
003001 分类 2
003001001 直管 3
003001001001 直管 4现在只要取第一级直管001001 直管 2
002 直管 1
003001001 直管 3求SQL,谢谢了!
select * from tb a
where 类型='直管'
and not exists(select 1 from tb where 类型='直管' and charindex(编码,a.编码)=1)
create table tb(编码 varchar(20),类型 varchar(8), 级数 int)
insert tb
select '001','分类',1 union all
select '001001','直管',2 union all
select '001001001','直管',3 union all
select '002','直管',1 union all
select '003','分类',1 union all
select '003001','分类',2 union all
select '003001001','直管',3 union all
select '003001001001','直管',4
select * from tb a
where 类型<>'分类'
and not exists (select 1 from tb b where 类型<>'分类'
and b.编码 like left(a.编码,3)+'%'
and b.级数<a.级数)drop table tb
/*
编码 类型 级数
-------------------- -------- -----------
001001 直管 2
002 直管 1
003001001 直管 3(所影响的行数为 3 行)*/
insert tb
select '001','分类',1 union all
select '001001','直管',2 union all
select '001001001','直管',3 union all
select '002','直管',1 union all
select '003','分类',1 union all
select '003001','分类',2 union all
select '003001001','直管',3 union all
select '003001001001','直管',4
select * from tb a
where 类型='直管'
and not exists(select 1 from tb where 类型='直管'
and charindex(编码,a.编码)=1 and 编码<>a.编码)
/*
编码 类型 级数
-------------------- -------- -----------
001001 直管 2
002 直管 1
003001001 直管 3
distinct b.*
from
tb a
cross apply
(select * from tb where 类型='直管' and 编码<>a.编码 and charindex(编码,a.编码)=1)b