I’m testing SQL query which calculates the total weight of a components. These are the tables structure:
Here I store the key of the parent component and the child component:
-- 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)
Here I store the id of the component and the weight:
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)
/
I want to create tree with components and using SQL query to calculate the total weight of all components. I made this SQL query:
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;
But for some reason I cannot get the proper result. I only get the first children of the first parent. The goal is to use the COMPONENT table to get the all children and sub children and to calculate the weight.
Can you help me to find where I’m wrong?
You can use a hierarchical query in Oracle to return the tree of components, see http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm
http://www.sqlfiddle.com/#!4/def0e/2