Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

como obter esse resultado usando a consulta oracle em estrutura hierárquica


Acho que consegui fazer isso com funções analíticas (não elegantemente, mas mesmo assim) -
with
grps as(
    select marker
    from(
        select collateral_num,
               loan_num,
               rownum as marker,
               case when lead(loan_num,1) over (order by collateral_num) <> loan_num
                         and lead(collateral_num,1) over (order by collateral_num) <> collateral_num
                    then 1
                    when lead(loan_num,1) over (order by collateral_num) is null
                    then 1
                    else null end as grp
          from  loan
         order by collateral_num
        )
    where grp is not null
       )
, marked as(
    select loan.*, grps.*, row_number() over(partition by marker order by collateral_num) as splitter
    from loan, grps
           )
select  collateral_num,
        min(collateral_num) over (partition by marker) as min_collateral_num,
        loan_num
from    marked y
where   splitter <= marker
    and (splitter > (select max(x.marker) from marked x where x.marker < y.marker)
     or marker = (select min(marker) from marked))

Veja sqlfiddle em http://sqlfiddle.com/#!4/cfb1a7/40/ 0