如何解决选择父行并包括子项成本
def get_largest_city():
max_population = max(this_dict.items(),key=lambda item: int(item[1]["population"]))
return max_population[1]["capital"]
我想选择父级行,并在父级中包括子级的成本:
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 acttoolcost from dual
union all
select 'WO37429' as wonum,100 as actmatcost,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
在Oracle 18c中是否有一种简洁的方法?
(我的目标是使sql尽可能简单/可读。)
解决方法
对于一级父母/子女关系,如您的示例数据所示,我建议:
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)
,
对于具有多个级别的层次结构,您可以使用CONNECT_BY_ROOT( ... )
,然后使用GROUP BY
:
SELECT root_wonum AS wonum,SUM( actlabcost ) AS total_actlabcost,SUM( actmatcost ) AS total_actmatcost,SUM( actservcost ) AS total_actservcost,SUM( acttoolcost ) AS total_acttoolcost
FROM (
SELECT CONNECT_BY_ROOT( wonum ) AS root_wonum,actlabcost,actmatcost,actservcost,acttoolcost
FROM workorder
START WITH parent IS NULL
CONNECT BY PRIOR wonum = parent
)
GROUP BY root_wonum;
其中,用于测试数据:
CREATE TABLE workorder ( wonum,parent,acttoolcost ) as
select 'WO37342',null,297.36,200,0 from dual union all
select 'WO37427','WO37342',99.12,0 from dual union all
select 'WO37429',100,0 from dual;
输出:
WONUM | TOTAL_ACTLABCOST | TOTAL_ACTMATCOST | TOTAL_ACTSERVCOST | TOTAL_ACTTOOLCOST :------ | ---------------: | ---------------: | ----------------: | ----------------: WO37342 | 495.6 | 300 | 0 | 0
db 提琴here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。