sql - 计算路段成本

标签 sql postgresql algorithm

路线表:

route_id | points 
       1 | [A,B] 
       2 | [L,G,C,F,E]

包含路线段成本的表格:

route_id | point A | pointB | cost
       1 | A       | B      |   10
       2 | L       | G      |   10
       2 | G       | C      |   20
       2 | C       | F      |   15
       2 | F       | E      |   13

需要计算route_id=2中点'G'和'E'之间的费用

最佳答案

您可以使用“Recursive With Clause”实现您想要的结果。

表格:

create table test(
route_id int, 
pointA char,
 pointB char, 
 cost int
);

值(value)观:

insert into test values(1 ,'A','B',10),
(2 ,'L','G',10),
(2 ,'G','C',20),
(2 ,'C','F',15),
(2 ,'F','E',13)

递归查询:

WITH RECURSIVE routecost AS (
SELECT pointA, pointB ,cost  /* non recursive part */ 
FROM test                   
WHERE pointA = 'G'
  and route_id = 2 
UNION ALL
SELECT b.pointA, a.pointB, a.cost + b.cost   /* recursive part */               
FROM test a                
JOIN routecost b ON(a.pointA = b.pointB)    
  where a.route_id = 2
)
SELECT * FROM routecost
where pointB = 'E'

解释:

  1. 先用非递归的pointA和route_id过滤query 部分。
  2. 然后在递归部分按照查询所示加入它并添加成本
  3. 我每次都获取 b.pointA(在非递归部分),因为我们 需要起点。
  4. 然后最后我将它过滤到 pointB 值以获得所需 结果。

Reference: Recursive with clause

关于sql - 计算路段成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595811/

相关文章:

sql - 使用 Django ORM 执行复杂的自引用查询

java - 在不将所有比较数据加载到内存的情况下比较两组 XML 数据

javascript - 如何在 javascript 中从 PHP 调用函数,Ajax 不返回任何内容

mysql - SQL Sum 返回错误值

sql - 添加带有 SQL 导入任务的标志

sql - 事务回滚在 Postgresql 中不起作用

sql - 滚动平均postgres

sql - 如何用 except 替换 2 个查询

algorithm - 包含所有对象的最小区间

python - 缩短一个语句被反转的 if 语句