How to retrieve all recursive children of parent row in Oracle SQL?

后端 未结 2 683
温柔的废话
温柔的废话 2021-01-31 21:20

I\'ve got a recursive query that\'s really stretching the limits of this Java monkey\'s SQL knowledge. Now that it\'s finally 1:30 in the AM, it\'s probably time to start looki

2条回答
  •  -上瘾入骨i
    2021-01-31 21:39

    @AlexPoole answer is great, I just want to extend his answer with more intuitive variant of query for summing values along a path.
    This variant based on recursive subquery factoring feature, introduced in Oracle 11g R2.

    with recursion_view(base, parent_id, child_id, qty) as (
       -- first step, get rows to start with
       select 
         parent_id base, 
         parent_id, 
         child_id, 
         qty
      from 
        md_boms
    
      union all
    
      -- subsequent steps
      select
        -- retain base value from previous level
        previous_level.base,
        -- get information from current level
        current_level.parent_id,
        current_level.child_id,
        -- accumulate sum 
        (previous_level.qty + current_level.qty) as qty 
      from
        recursion_view previous_level,
        md_boms        current_level
      where
        current_level.parent_id = previous_level.child_id
    
    )
    select 
      base, parent_id, child_id, qty
    from 
      recursion_view
    order by 
      base, parent_id, child_id
    

    SQLFiddle example (extended with one data row to demonstrate work with more then 2 levels)

提交回复
热议问题