如何计算Oracle中所有组件的总权重

时间:2013-01-30 13:37:47

标签: sql oracle oracle11g

我正在测试SQL查询,它计算组件的总重量。这些是表结构:

这里我存储了父组件和子组件的键:

-- CREATE TABLES SECTION -------------------------------------------------

-- TABLE COMPONENT

CREATE TABLE COMPONENT(
  COMPONENTID NUMBER NOT NULL,
  FKCOMPONENTID NUMBER,
  COMPONENTSTATSID INTEGER NOT NULL
)
/

-- ADD KEYS FOR TABLE COMPONENT

ALTER TABLE COMPONENT ADD CONSTRAINT COMPONENTID PRIMARY KEY (COMPONENTID)

这里我存储了组件的id和权重:

CREATE TABLE COMPONENTSTATS(
  COMPONENTSTATSID INTEGER NOT NULL,
  COMPONENTTYPEID INTEGER NOT NULL,
  NAME VARCHAR2(200 ) NOT NULL,
  SERIALNUMBER VARCHAR2(150 ),
  WEIGHTKG NUMBER(14,4),
  SIZEWEIGHTMILIM NUMBER(14,4),
)
/

-- ADD KEYS FOR TABLE COMPONENTSTATS

ALTER TABLE COMPONENTSTATS ADD CONSTRAINT COMPONENTSTATSID PRIMARY KEY (COMPONENTSTATSID)
/

我想用组件创建树,并使用SQL查询来计算所有组件的总重量。我做了这个SQL查询:

select c.componentid, nvl(cs.weightkg, 0) as componentkg,
 (case 
    when exists (select 1 from component where fkcomponentid = c.componentid) then
      (select sum(nvl(cs.weightkg, 0)) as kg FROM  component a, componentstats cs  where a.fkcomponentid is not null and cs.componentstatsid = a.componentstatsid and a.fkcomponentid = c.componentid)
 end) as childrenkg
 from component c, componentstats cs  
 where 
 cs.componentstatsid = c.componentstatsid
 and componentid = ?
 order by c.componentid;

但由于某种原因,我无法得到正确的结果。我只得到第一个父母的第一个孩子。目标是使用COMPONENT表来获取所有子项和子项,并计算权重。

你能帮我找到我错的地方吗?

1 个答案:

答案 0 :(得分:1)

您可以在Oracle中使用分层查询来返回组件树,请参阅http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm

select componentid,
         (select sum(cs.weightkg)
            from component c2, componentstats cs
           where c2.componentstatsid = cs.componentstatsid
               start with c2.componentid = c1.componentid
         connect by prior c2.componentid = c2.fkcomponentid) sum_weightkg
from component c1
start with c1.fkcomponentid is null
connect by prior componentid = fkcomponentid;

http://www.sqlfiddle.com/#!4/def0e/2