汇总所有子级数据

时间:2017-12-07 10:47:12

标签: sql oracle oracle11g

我有一个要求,我需要总结一个节点的所有子节点。

enter image description here

输出应该是

{
    "error": {
        "code": "BadRequest",
        "message": "Invalid filter clause",
        "innerError": {
            "request-id": "906cdcb0-cf3d-4eda-8c0b-2cdd9002cc4f",
            "date": "2017-12-07T10:45:41"
        }
    }
}

我尝试使用diff查询,但没有获得所需。请帮助

D023343 120
D022959 120
D023375 50
D035738 10
D024481 0

请帮助。

由于

2 个答案:

答案 0 :(得分:2)

使用分层查询遍历层次结构,使用CONNECT_BY_ROOT()引用层次结构的顶部 - 然后可以使用该查询对查询进行分组以获取后代的总数。

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE your_table( parent, child, sales ) AS
SELECT 'D023343', 'D022959',  0 FROM DUAL UNION ALL
SELECT 'D022959', 'D023375', 60 FROM DUAL UNION ALL
SELECT 'D023375', 'D035738', 50 FROM DUAL UNION ALL
SELECT 'D035738', 'D024481', 10 FROM DUAL;

查询1

SELECT root,
       SUM( sales ) AS total_sales
FROM   (
  SELECT CONNECT_BY_ROOT( parent ) AS root,
         sales
  FROM   your_table
  CONNECT BY PRIOR child = parent
)
GROUP BY root

<强> Results

|    ROOT | TOTAL_SALES |
|---------|-------------|
| D023375 |          60 |
| D035738 |          10 |
| D023343 |         120 |
| D022959 |         120 |

如果您想要没有销售的叶子,那么您需要执行附加

之类的操作
UNION ALL
SELECT child, 0 FROM your_table

到内部查询。

答案 1 :(得分:1)

您可以使用SQL-99 standard中定义的递归公用表表达式。 Oracle称之为recursive subquery factoring。您还需要做一些事情来获得结果中0销售的最后一条记录,因为没有明确定义该销售额的记录。

以下是此类查询的外观:

with base(parent, child, sales) as (
    select parent, child, sales
    from   tbl
    union all -- add the 0 sales records
    select child, null, 0
    from   tbl
),
rec(parent,child,sales) as ( -- recursive query
    select parent, child, sales
    from   base
    union all
    select rec.parent, base.child, base.sales
    from   base
    inner join rec on base.parent = rec.child
)
select   parent, sum(sales)
from     rec
group by parent
order by 1

注意:从Oracle 11g第2版开始支持此语法。