如何在SQL查询中聚合数字

时间:2013-01-30 14:47:27

标签: sql oracle oracle11g

我有这个SQL查询,它搜索父母和子女并计算权重。

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 = 100
connect by prior componentid = fkcomponentid

问题在于我希望SQL查询将总权重作为数字返回(它发现要聚合的所有数字)。

这是我得到的结果:

COMPONENTID            SUM_WEIGHTKG           
---------------------- ---------------------- 
201                    410                    
231                    210                    
323                    10

你能帮我改写一下SQL查询吗?

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

1 个答案:

答案 0 :(得分:1)

select max(sum_weightkg) from
(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 = 100
   connect by prior componentid = fkcomponentid);

我不确定这是最好的方法,但它应该有用。