部门代码  级别             上级代码
01        1          null
0101      2          01        
010101    3          0101      
010102    3          0101      
0102      2          01        
010201    3          0102      
010202    3          0102      
02        1          null
0201      2          02        
0202      2          02     用sql语句查询后,将结果显示成为
01  0101     010101
01  0101     010102
01  0102     010201
01  0102     010202
02  0201     null
02  0202     null如何写啊?

解决方案 »

  1.   

    select right(部门代码,2),上级代码,部门代码 from 表 order by 部门代码
      

  2.   

    create table A
    (
       id varchar(10),
       lev int,
       p_id varchar(10)
    )insert A select '01',1, null
    insert A select '0101',2,'01'        
    insert A select '010101',3,'0101'      
    insert A select '010102',3,'0101'      
    insert A select '0102',2,'01'        
    insert A select '010201',3,'0102'      
    insert A select '010202',3,'0102'      
    insert A select '02',1,null
    insert A select '0201',2,'02'        
    insert A select '0202',2,'02' 
    select A1.id,Az.id2,Az.id3 from
    (select id,p_id from A where lev=1) A1 left join 
    (select a2.id as id2,a3.id as id3,A2.p_id
    from
    (select id,p_id from A where lev=2) A2 left join (select id,p_id from A where lev=3) A3 on a2.id=a3.p_id) Az on A1.id =Az.p_id
      

  3.   


    select t1.部门代码 as 一级部门,t2.部门代码 as 二级部门,t3.部门代码 as 三级部门
    from 表 t1 left join 表 t2 on  t1.上级代码 = t2.部门代码 and t1.级别= 1 and t2.级别=2
    left join 表 t3 on  t2.上级代码 = t3.部门代码 and t2.级别= 2 and t3.级别=3