根据同一个表

时间:2018-03-02 13:45:31

标签: sql postgresql

我想要检索的结果如下所示。我已设法检索原点,目的地,出发地,到达地点和价格安装,但我无法弄清楚如何获得两次旅行的最低座位和驾驶这两次旅行的司机。不要担心driverName不是原子的。

Result I want to retrieve

到目前为止我的查询:

SELECT t1.origin, t2.destination, t1.departure, t2.arrival, t1.priceAmount + t2.priceAmount AS priceAmount
    FROM trip t1, trip t2
    WHERE t1.origin = 'Stockholm'
    AND t1.destination = 'Copenhagen'
    AND t2.origin = 'Copenhagen'
    AND t2.destination = 'Berlin';

这是旅行表:

create table trip(
    tripId serial not null,
    origin varchar(50) not null,
    destination varchar(50) not null,
    departure timestamp not null,
    arrival timestamp not null,
    driverPnr varchar(13),
    priceAmount integer not null,
    seats integer not null,
    primary key (tripId),
    foreign key (origin) references busstop(city),
    foreign key (destination) references busstop(city),
    foreign key (driverPnr) references driver(driverPnr)
);

1 个答案:

答案 0 :(得分:2)

我认为LEAST功能是你想要的:

LEAST(t1.seats, t2.seats)

如果交叉连接是故意的,那么如果使用

,查询将变得更具可读性
FROM trip t1 CROSS JOIN trip t2