计算路径数

时间:2019-03-04 05:48:28

标签: sql postgresql recursive-query

我有一个trainschedule表,它像:-

 train_id | source  | destination | distance | departure_time | arrival_time 
----------+---------+-------------+----------+----------------+--------------
 22435    | Kolkata | Bhopal      |     1200 | 08:00:00       | 17:00:00
 21484    | Mumbai  | Jaipur      |      500 | 13:23:44       | 13:23:45
 21424    | Delhi   | Mumbai      |      800 | 13:23:44       | 15:05:40
 12456    | Bhopal  | Mumbai      |      800 | 11:00:00       | 23:00:00
 12453    | Banaras | Mumbai      |      500 | 11:00:00       | 21:00:00
 21514    | Jaipur  | Madras      |     1500 | 10:05:00       | 13:23:45
 21414    | Delhi   | Kolkata     |      800 | 14:05:00       | 15:05:40
 23432    | Bhopal  | Hyderabad   |      670 | 12:00:00       | 20:20:00
(8 rows)

鉴于源城市(例如德里)和目的地城市(例如孟买),我应该返回这两个城市之间的路径数。

我不知道该怎么找到,我所能想到的只是:-

with recursive path(f,t) as(
    select source,destination
    from trainschedule
    union
    select trainschedule.source,path.t
    from trainschedule,path
    where trainschedule.destination=path.f)
select t 
from path;

它给了我从给定城市可以到达的所有城市。我现在不知道该如何进行。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

您已经完成了递归cte中的所有艰苦工作。您只需要进行一项更改,即使用UNION ALL而不是UNION,这样就可以为从一个城市到另一个城市的每条路径获取一行。然后,您只需选择每对城市,然后在cte中计算该对城市的行数即可:

with recursive path(f,t) as(
    select source,destination
    from trainschedule
    union all
    select trainschedule.source,path.t
    from trainschedule,path
    where trainschedule.destination=path.f)
select f, t, count(*)
from path
group by f, t
order by f, t;

输出(用于您的示例数据):

f       t           count
Banaras Jaipur      1
Banaras Madras      1
Banaras Mumbai      1
Bhopal  Hyderabad   1
Bhopal  Jaipur      1
Bhopal  Madras      1
Bhopal  Mumbai      1
Delhi   Bhopal      1
Delhi   Hyderabad   1
Delhi   Jaipur      2
Delhi   Kolkata     1
Delhi   Madras      2
Delhi   Mumbai      2
Jaipur  Madras      1
Kolkata Bhopal      1
Kolkata Hyderabad   1
Kolkata Jaipur      1
Kolkata Madras      1
Kolkata Mumbai      1
Mumbai  Jaipur      1
Mumbai  Madras      1

Demo on dbfiddle