SQL从多个表中检索信息

时间:2012-11-04 18:36:16

标签: sql sql-server

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

我需要找到路径为km的路径,其中id = 1从站1开始到达站4.因此路由1将从4个站(数量可能更多或更少)通过。我需要找到火车穿越所有4个车站的距离。其中:5 + 10 + 15 = 30

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

下面是表格(我希望你理解结构):

您可以看到表格here

的图片
route - station
-----------------------
1     - 1    
1     - 2    
1     - 3    
1     - 4


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

1 个答案:

答案 0 :(得分: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=#