求一SQL语句。
我有一代码如下,小数点代表级别,想排除最下级的代码,只取出没下级代码的行。这表没记录是否最明细级,也没记录上级代码。
KD01
KD01.0024
KD01.0024.0022
KD01.0024.0024
KD01.0011
KD01.0011.0009
KD01.0011.0010
KD01.0011.0010.0001
KD01.0011.0011
KD01.0011.0012
KD01.0011.0005
KD01.0011.0005.0003
[解决办法]
;with cte(col) as
(
select 'KD01'
union all select 'KD01.0024'
union all select 'KD01.0024.0022'
union all select 'KD01.0024.0024'
union all select 'KD01.0011'
union all select 'KD01.0011.0009'
union all select 'KD01.0011.0010'
union all select 'KD01.0011.0010.0001'
union all select 'KD01.0011.0011'
union all select 'KD01.0011.0012'
union all select 'KD01.0011.0005'
union all select 'KD01.0011.0005.0003'
)
select *
from cte a
where exists(select 1 from cte b where len(a.col)>LEN(b.col) and CHARINDEX(b.col,a.col)=0)
/*
col
KD01.0024.0022
KD01.0024.0024
KD01.0011.0009
KD01.0011.0010
KD01.0011.0010.0001
KD01.0011.0011
KD01.0011.0012
KD01.0011.0005
KD01.0011.0005.0003
*/
--没有下级的行。这是你想要的结果吗?
只取出没下级代码的行
with cte(col) as
(
select 'KD01'
union all select 'KD01.0024'
union all select 'KD01.0024.0022'
union all select 'KD01.0024.0024'
union all select 'KD01.0011'
union all select 'KD01.0011.0009'
union all select 'KD01.0011.0010'
union all select 'KD01.0011.0010.0001'
union all select 'KD01.0011.0011'
union all select 'KD01.0011.0012'
union all select 'KD01.0011.0005'
union all select 'KD01.0011.0005.0003'
)
select *
from cte a
WHERE EXISTS(SELECT 1 FROM cte WHERE LEN(col)>LEN(a.col) AND col LIKE a.col+'%')