现有如下结构表 产品表 product 
id       name     parent_id
----------------------------
001 电子类       0
002 金属类       0
004 电子电容     001
005 电子电阻     001
006 有色金属     002
007 无色金属     002消耗表 consume
id     num 
----------------
004   50
005   125
006   39
007   12要统计得到如下结果:
id       name        num
----------------------------
001 电子类         175
004       电子电容      50
005       电子电阻     125
002 金属类         51
006   有色金属     39
007   无色金属     12问:如何得到上面所列的统计结果?(即统计结果中有父类的合计同时还得在他的先面列出子类)

解决方案 »

  1.   

    select a.id,a.name,nvl((select sum(num) from consume where id in (select id from product where parent_id = a.id)),0) + nvl((select sum(num) from consume where id = a.id),0) from product a;
      

  2.   

    select p_id,[name],sum(num)as num from (
    select a.p_id,c.name,b.num from product a inner join consume b 
    on a.id=b.id inner join product c on a.p_id=c.id
    union
    select a.id,a.name,b.num from product a inner join consume b 
    on a.id=b.id  ) m
    group by p_id,[name]
    order by p_id
      

  3.   

    SQL> select a.id,a.name,
      2  (select sum(num) from product b,consume c 
      3  where b.id = c.id(+) start with b.id = a.id 
      4  connect by prior b.id = b.parent_id) num 
      5  from product a;ID         NAME                        NUM
    ---------- -------------------- ----------
    001        电子类                      175
    002        金属类                       51
    004        电子电容                     50
    005        电子电阻                    125
    006        有色金属                     39
    007        无色金属                     12已选择6行。
      

  4.   

    SQL> select a.id,a.name,
      2  (select sum(num) from product b,consume c 
      3  where b.id = c.id(+) start with b.id = a.id 
      4  connect by prior b.id = b.parent_id) num 
      5  from product a start with parent_id = 0 connect by prior a.id = a.parent_id;ID         NAME                        NUM
    ---------- -------------------- ----------
    001        电子类                      175
    004        电子电容                     50
    005        电子电阻                    125
    002        金属类                       51
    006        有色金属                     39
    007        无色金属                     12已选择6行。