从父行中选择属性并包括子项的费用

问题描述

我有一个包含父级和子级WO的WORKORDER表。层次结构只有两个级别:父级和子级(没有孙级,等等)


with workorder as (
select 'WO37342' as wonum,null as parent,'WINTER STORM' as classification,297.36 as actlabcost,200 as actmatcost from dual
union all
select 'WO37427' as wonum,'WO37342' as parent,'ANTI-ICING'   as classification,99.12 as actlabcost,0 as actmatcost from dual
union all
select 'WO37429' as wonum,'SNow FENCE'   as classification,100 as actmatcost from dual
)
select
    * 
from
    workorder


WONUM     PARENT    CLASSIFICATION ACTLABCOST ACTMATCOST
-------   -------   -------------- ---------- ----------
WO37342             WINTER STORM       297.36        200
WO37427   WO37342   ANTI-ICING          99.12          0
WO37429   WO37342   SNow FENCE          99.12        100

我想从父行中选择属性,并包括子项的费用:

WONUM     CLASSIFICATION ACTLABCOST ACTMATCOST
-------   -------------- ---------- ----------
WO37342   WINTER STORM        495.6        300

在Oracle 18c中是否有一种简洁的方法

(我的目标是使sql尽可能简单/可读。)

解决方法

您可以使用聚合:

select coalesce(parent,wonum) as wonum,max(case when parent is null then classification end) as classification,sum(ACTLABCOST) as ACTLABCOST,sum(ACTMATCOST) as ACTMATCOST
from t
group by coalesce(parent,wonum);

这对我来说似乎很简单。