このようなものですが、ステーションの順序、距離の定義方法などには多くの仮定があります。これはアプローチの例にすぎません (および Postgresql を使用):
create table route(route_id int, station_id int);
create table distance(station1_id int, station2_id int, km int);
insert into route values(1, 1);
insert into route values(1, 2);
insert into route values(1, 3);
insert into route values(1, 4);
insert into distance values(1, 2, 5);
insert into distance values(2, 3, 10);
insert into distance values(3, 4, 15);
select route_id, sum(km)
from (select route_id, station_id
,lead(station_id) over(partition by route_id order by station_id) AS next_station_id
from route
) a
,distance d
where d.station1_id = a.station_id
and d.station2_id = a.next_station_id
group by route_id;
出力例:
postgres=# select route_id, station_id
postgres-# ,lead(station_id) over(partition by route_id order by s
tation_id) AS next_station_id
postgres-# from route;
route_id | station_id | next_station_id
----------+------------+-----------------
1 | 1 | 2
1 | 2 | 3
1 | 3 | 4
1 | 4 |
(4 rows)
postgres=# select route_id, station_id, next_station_id, d.km
postgres-# from (select route_id, station_id
postgres(# ,lead(station_id) over(partition by route_id order by s
tation_id) AS next_station_id
postgres(# from route
postgres(# ) a
postgres-# ,distance d
postgres-# where d.station1_id = a.station_id
postgres-# and d.station2_id = a.next_station_id;
route_id | station_id | next_station_id | km
----------+------------+-----------------+----
1 | 1 | 2 | 5
1 | 2 | 3 | 10
1 | 3 | 4 | 15
(3 rows)
postgres=# select route_id, sum(km)
postgres-# from (select route_id, station_id
postgres(# ,lead(station_id) over(partition by route_id order by s
tation_id) AS next_station_id
postgres(# from route
postgres(# ) a
postgres-# ,distance d
postgres-# where d.station1_id = a.station_id
postgres-# and d.station2_id = a.next_station_id
postgres-# group by route_id;
route_id | sum
----------+-----
1 | 30
(1 row)
postgres=#