Select 父行的属性(包括子行的成本)

Select attributes from parent rows (and include cost of children)

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


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, 'WO37342' as parent, 'SNOW FENCE'   as classification,  99.12 as actlabcost, 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

我想 select 父行的属性并包括子行的成本:

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

在 Oracle 18c 中是否有一种简洁的方法可以做到这一点?

(我的目标是 SQL 尽可能 simple/readable。)

您可以使用聚合:

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);

这对我来说似乎很简单。