我有这个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;
如何将其重写为分层查询?这可能吗?
编辑:计划的图片
答案 0 :(得分:1)
基本查询如下:
select the_level, c.componentid, NVL( cs.weightkg,0) as componentkg
from ( select level the_level, componentid from component
start with componentid = ?
connect by fkcomponentid = prior componentid
) c
join componentstats using (componentstatsid)
order by the_level, c.componentid
这将为您提供每个组件及其重量。然后,您可以通过各种方式进行分组和求和 - 如果您想要原始查询中子组件权重的总和,则可以按级别进行分组,如果您只想要总权重,则可以按一切进行分组。