Wednesday, August 26, 2020

Recursive "WITH" clause

Code:

create table flights (
    source          varchar(10),
    destination     varchar2(10),
    flight_time     number(3,1)
    );
    
insert into flights values ('Bei Jing', 'Shang Hai',2);
insert into flights values ('Shang Hai', 'Singapore',5.5);
insert into flights values ('Singapore', 'Sydney',9);

commit;
WITH Reachable_From (source, destination, total_flight_time) 
AS
(
    SELECT source, destination, flight_time from flights
  UNION ALL
    SELECT incoming.source, outgoing.destination, 
        incoming.total_flight_time+outgoing.flight_time
    FROM Reachable_From incoming, flights outgoing
    WHERE incoming.destination=outgoing.source
)
SELECT source, destination, total_flight_time
FROM Reachable_From;
Output:


No comments:

Post a Comment