首页 > 解决方案 > 选择父行并包含子行的成本

问题描述

我有一个 WORKORDER 表,其中包含父级和子级 WO:

with workorder as (
select 'WO37342' as wonum,      null as parent, 297.36 as actlabcost, 200 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
union all
select 'WO37427' as wonum, 'WO37342' as parent,  99.12 as actlabcost,   0 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
union all
select 'WO37429' as wonum, 'WO37342' as parent,  99.12 as actlabcost, 100 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
)
select
    * 
from
    workorder

 WONUM   PARENT  ACTLABCOST ACTMATCOST ACTSERVCOST ACTTOOLCOST
 ------- ------- ---------- ---------- ----------- -----------
 WO37342             297.36        200           0           0
 WO37427 WO37342      99.12          0           0           0
 WO37429 WO37342      99.12        100           0           0

我想选择父行并在父母中包括孩子的成本:

 WONUM    ACTLABCOST ACTMATCOST ACTSERVCOST ACTTOOLCOST
 ------- ----------- ---------- ----------- -----------
 WO37342       495.6        300           0           0

在 Oracle 19c 中有一种简洁的方法吗?

(我的目标是让 SQL 尽可能简单/可读。)

标签: sqloraclesummaximooracle19c

解决方案


对于单级父/子关系,如您的示例数据所示,我建议:

select  
    coalesce(parent, wonum) wonum
    sum(actlabcost)  actlabcost, 
    sum(actmatcost)  actmatcost,
    sum(actservcost) actservcost,
    sum(acttoolcost) acttoolcost
from workorder wo
group by coalesce(parent, wonum)

推荐阅读