select [ID],
一层类别=max(case when charindex(编号,'0c')=0 then 名称 else null end),
二层类别=max(case when charindex(编号,'0c0f')=0 then 名称 else null end),
三层类别=max(case when charindex(编号,'0c0f01'=0) then 名称 else null end)
from 表一 group by [ID]

解决方案 »

  1.   

    --> 测试数据:#
    if object_id('tempdb.dbo.#') is not null drop table #
    create table #(ID int, 名称 varchar(8), 编号 varchar(8))
    insert into #
    select 25, '茅台', '0c0f01' union all
    select 50, '食品', '0c' union all
    select 72, '酒', '0c0f'select a.ID, 一层类别 = b.名称, 二层类别 = c.名称, 三层类别 = d.名称 from # a
    left join # b on left(a.编号,2)=b.编号
    left join # c on left(a.编号,4)=c.编号 and len(c.编号)=4
    left join # d on a.编号=d.编号 and len(d.编号)=6/*
    ID          一层类别 二层类别 三层类别
    ----------- -------- -------- --------
    25          食品     酒       茅台
    50          食品     NULL     NULL
    72          食品     酒       NULL
    */
      

  2.   

    --> 测试数据:#
    if object_id('tempdb.dbo.#') is not null drop table #
    create table #(ID int, 名称 varchar(8), 编号 varchar(8))
    insert into #
    select 25, '茅台', '0c0f01' union all
    select 50, '食品', '0c' union all
    select 72, '酒', '0c0f'select
    ID,
    一层类别=(select 名称 from # where 编号=left(t.编号,2)),
    二层类别=(select 名称 from # where 编号=left(t.编号,4) and len(编号)=4),
    二层类别=(select 名称 from # where 编号=t.编号 and len(编号)=6)
    from # t/*
    ID          一层类别 二层类别 三层类别
    ----------- -------- -------- --------
    25          食品     酒       茅台
    50          食品     NULL     NULL
    72          食品     酒       NULL
    */