0

我有一个关于 sql 的问题,我需要知道我是否可以只使用 sql 检索结果。

我需要找到从 1 号站开始并到达 4 号站的 id=1 的路线的公里距离。所以路线 1 将从 4 个站经过(数量可能或多或少)。我需要找到一列火车穿越所有 4 个车站的距离。即:5+10+15=30

是否可以仅使用 SQL 获得答案?

以下是表格(我希望您了解结构):

你可以在这里看到一张桌子的图片

route - station
-----------------------
1     - 1    
1     - 2    
1     - 3    
1     - 4


station1 - station2 - distance (km)
------------------------------------
1        - 2        -   5
2        - 3        -   10
3        - 4        -   15
4

1 回答 1

0

像这样的东西,但是对站点的排序,距离如何定义等有很多假设。这只是一种方法的示例(并使用 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=#
于 2012-11-04T19:06:46.927 回答