Oracle
 sql >> Database >  >> RDS >> Oracle

come ottenere questo risultato usando la query Oracle nella struttura gerarchica

Penso di essere riuscito a farlo con funzioni analitiche (non elegantemente, ma comunque) -

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))

Vedi sqlfiddle su http://sqlfiddle.com/#!4/cfb1a7/40/ 0