根据同一个表中的两行检索一行

问题描述 投票:0回答:1

我想要检索的结果如下所示。我已设法检索原点,目的地,出发地,到达地点和价格安装,但我无法弄清楚如何获得两次旅行的最低座位和驾驶这两次旅行的司机。不要担心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)
);
sql postgresql
1个回答
2
投票

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

LEAST(t1.seats, t2.seats)

如果交叉连接是故意的,那么如果您使用,查询将变得更具可读性

FROM trip t1 CROSS JOIN trip t2
© www.soinside.com 2019 - 2024. All rights reserved.