计算路径数

Counting number of paths

我有一个 table 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)

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

我不知道如何找到它,我所能想到的是:-

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;

它为我提供了从给定城市可到达的所有城市。我不知道现在该怎么办。任何帮助,将不胜感激。谢谢!

您已经完成了递归 cte 中的所有艰苦工作。您只需要做一个更改,即使用 UNION ALL 而不是 UNION,这样您就可以得到从一个城市到 every 条路径的一行其他。然后你可以 select 每对城市并计算 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