0

コンポーネントの総重量を計算する 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 テーブルを使用してすべての子とサブ子を取得し、重みを計算することです。

私が間違っている場所を見つけるのを手伝ってもらえますか?

4

1 に答える 1

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

于 2013-01-30T13:48:13.510 に答える