UNIT        NAME        NUM     FATHERCODE
1   0124 供电公司    7
2   0126 水供电公司 4
3   hs02 1县电力局 35 0126
4   hs05 2县电力局 80      0126 
帮忙看个问题,如何用sql语句把FATHERCODE不为空的行的num的值加到入到他父级的peonum中,比如这个表的期待结果就是将3,4行的num累加到第二行的num上,第二行的num值应为119

解决方案 »

  1.   

    select a.unit,a.nem,nvl(a.num,0)+nvl(b.num,0) num
    from tb a
    left join (select fathercode,sum(num) num from tb where fathercode is not null gorup by fathercode)b 
    on a.unit=b.fathercode
    where a.fathercode is null;
      

  2.   

    select code,sum(num) from 
    (select fathercode as code,num from view_test where fathercode is not null
    union
    select code,num from view_test where fathercode is null) t
    group by code谢谢二楼...问题已解决,但是应该这段代码看比较起应该比较明白一点,总觉得还可以优化.....有高人看到的话还望指点一二....