如下表
单位级次编码表
级次编码
001   
001002
001002003
001003
001003001
001003002   
001的下级单位就是前面有001的
001002的下级单位就是前面有001002的数据表
单位         金额
001002003    100
001003001    200
001003002    100现在要得到这样的表
单位编码   金额
001         400
001002      100
001003      300
001002003    100
001003001    200
001003002    100
请问改怎么写最简单,而且效率最高啊

解决方案 »

  1.   

    order by length(单位编码) asc, 单位编码 asc
      

  2.   

    select t.*,
    (select sum(je) from 数据表 v where substr(v.单位,1,length(t.编码))=t.编码)
    from t
      

  3.   

    select 
    decode(t.dan1,null,'',(decode(t.dan,null,t.dan1,(decode(t.danwei,null,t.dan,t.danwei))))) as dan
    ,t.jn
    from
    (
    select
    substr(c.danwei,1,3) as dan1,substr(c.danwei,1,6) as dan,c.danwei,sum(c.jine) as jn
    from
    datatable c
    group by rollup(substr(c.danwei,1,3) ,substr(c.danwei,1,6),c.danwei)
    )t
    where t.dan1 is not null
    order by length(dan),dan
    datatable 数据表
    danwei  单位 
    jine  金额