我有这张桌子:
我试图像这样解决这个问题:
提供一个返回最便宜费用的SQL查询 在每对城市之间飞行 假设我们愿意在途中停两次。例如,通过停止一次(in 丹佛),我们可以从SF到纽约获得700而不是750.在这个例子中,我们可以停下来 两次(在丹佛和芝加哥),但那会更贵(300 + 250 + 250 = 800)。“
问题编号4b的handout。
我只希望它只显示一个途中停止。
我到目前为止这个查询:
SELECT f1.fromCity, f2.toCity as destination, f1.toCity as scale, (MIN(f1.fare) + MIN(f2.fare)) as price
FROM flightfares f1, flightfares f2
WHERE f2.fromCity = f1.toCity
AND f1.fromCity != f2.toCity
GROUP BY f1.fromCity, f1.toCity, f2.toCity
HAVING MIN(f1.fare) AND MIN(f2.fare);
它显示从一个城市到另一个城市的数据,一站式和总价格。
我不知道该怎么做才能解决问题。 有人能为我提供想法或解决方案吗?
编辑: 加入版本?
SELECT f1.fromCity, f2.toCity as destination, f1.toCity as scale, (min(f1.fare) + min(f2.fare)) as price
FROM flighfares f1
JOIN flighfares f2 ON(f2.fromCity = f1.toCity AND f1.fromCity != f2.toCity)
GROUP BY f1.fromCity, f1.toCity, f2.toCity
HAVING min(f1.fare) AND min(f2.fare);
答案 0 :(得分:0)
此查询将根据您的给定数据仅解决一次停止。该答案仅基于所讨论的任务(4b)。希望这会有所帮助..
select * from
(select distinct start,dest,cost from pet
union
select distinct b.start,b.dest,MIN(total) cost
from
(select distinct a.start,(case when a.dest2 is null then dest1 else dest2 end)dest,(case when a.cost2 is NULL then a.cost1 else a.cost2+a.cost1 end) total
from (select t1.start,t1.dest dest1,t2.dest dest2,t1.cost cost1,t2.cost cost2
from pet t1 left join pet t2 on (t1.dest=t2.start and t1.start <> t2.dest))a)b group by b.start,b.dest order by cost)c
group by start,dest;
答案:
+---------+---------+------+
| start | dest | cost |
+---------+---------+------+
| Chicago | NY | 250 |
| Denver | Chicago | 250 |
| Denver | NY | 400 |
| Denver | SF | 250 |
| SF | Chicago | 550 |
| SF | Denver | 300 |
| SF | NY | 700 |
+---------+---------+------+
对于更多停留,此方法无法帮助您。再说这个答案只针对你提出的问题。
答案 1 :(得分:0)
也许这个:
SELECT First_airport, Final_airport, min(fare)
FROM (
SELECT
f1._from AS First_airport,
f1._to AS Mid_airport1,
f2._to AS Mid_airport2,
coalesce(f3._to, f2._to, f1._to) as Final_airport,
f1.cost + coalesce( f2.cost, 0) +coalesce( f3.cost, 0) as fare
FROM
flights f1 LEFT JOIN flights f2 ON
f1._to = f2._from LEFT JOIN flights f3 ON
f2._to = f3._from
UNION ALL SELECT
_from, '', '', _to, cost FROM flights
) t
GROUP BY First_airport, Final_airport
调整列名称。