求一简单树形结构的运算结果:
有表结构如下:
parentid,component,qty,batchqty
A B 100 1000
A C 1000 1000
B D 5 1000
B E 35 1000
C F 2000 2000
C H 1000 2000
需要计算出A、B、C、D、E、F、G、H各的数量。
结果为:A 1000
B 100
C 1000
D 0.5
E 3.5
F 1000
H 500

解决方案 »

  1.   

    CREATE TABLE tmpTree(
           ParentId VARCHAR2(10),
           component VARCHAR2(10),
           qty NUMBER,
           batchQty NUMBER);INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('', 'A', 1000, 1000);
    INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('A', 'B', 100, 1000);
    INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('A', 'C', 1000, 1000);
    INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('B', 'D', 5, 1000);
    INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('B', 'E', 35, 1000);
    INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('C', 'F', 2000, 2000);
    INSERT INTO tmpTree(ParentId, component, qty, batchQty) VALUES('C', 'H', 1000, 2000);SELECT component, qty, sys_connect_by_path(component, '\') path
      FROM tmpTree
     START WITH component = 'A'
    CONNECT BY PRIOR component = parentId
    ORDER BY component
      

  2.   

    TO:chanet(牧师) :
       非常谢谢你的帮助,我刚刚开始接触ORACLE ,还不怎么熟悉。
    在上面例子中, batchqty 是个很重要的字段,为什么你的语句中没有用到,还是我没看出来。
    C   F   2000   2000
    C   H   1000   2000
    其实是C,F,H之间的比例关系2000*C等价于,相当于2000*F+1000*Hsys_connect_by_path(component, '\') path该如何理解。