SQL,加入两个或多个表并返回结果

时间:2013-04-10 14:07:55

标签: sql join

CREATE TABLE Flight 
(
    FlightID INTEGER NOT NULL,
    FlightDate TIMESTAMP NOT NULL, 
    Origin VARCHAR(30) NOT NULL,
    Destination VARCHAR(30) NOT NULL,
    MaxCapacity INTEGER NOT NULL,
    PricePerSeat DECIMAL NOT NULL

)
CREATE TABLE FlightBooking 
(
    BookingID INTEGER NOT NULL,
    CustomerID INTEGER NOT NULL,
    FlightID INTEGER NOT NULL, 
    NumSeats INTEGER NOT NULL,
    Status CHAR(1) NOT NULL,
    BookingTime TIMESTAMP NOT NULL,
    TotalCost DECIMAL

)
status = Reserve, Held Cancelled or Expired (only reserved and held are taken into account)
CREATE TABLE SeatBooking
(
    BookingID INTEGER NOT NULL,
    PassengerID INTEGER NOT NULL,
    SeatNumber CHAR(4) 

)

无论如何,如果给出了flightid,我可以获得座位的状态,以及可用座位总数,预留座位总数和总座位数

2 个答案:

答案 0 :(得分:0)

  

无论如何,如果flightid是,我可以得到座位的状态   给定和总可用座位总数   预留座位和总持有座位

是的!我假设使用Oracle,SQL Server或DB2并使用CTE。如果您没有其中一个,则必须使用子查询或临时表。

如果'R'是状态代码,则预留座位总数(如果您想在where子句中使用,则可以将此限制为单个航班,但这些查询会为您提供所有航班ID的值):

SELECT SUM(NumSeats), FlightID
FROM FlightBooking 
WHERE Status = 'R'
GROUP BY FlightID

如果“H”是状态代码,则持有座位总数:

SELECT SUM(NumSeats), FlightID
FROM FlightBooking 
WHERE Status = 'H'
GROUP BY FlightID

总的可用座位是:

  WITH used AS
   (
      SELECT SUM(NumSeats) as used, FlightID
      FROM FlightBooking 
      WHERE Status in ('R','H')
      GROUP BY FlightID
   )
   SELECT F.MaxCapacity-U.Used, F.FlightID
   FROM used U
   JOIN Flight F ON U.FlightID = F.FlightID

答案 1 :(得分:0)

根据航班ID,您应该能够获得总可用座位,预留座位总数和总座位数,如下所示:

select MaxCapacity - Reserved - Held as Available, Reserved, Held
from
(select f.MaxCapacity,
        sum(case b.status when 'R' then b.NumSeats end) Reserved,
        sum(case b.status when 'H' then b.NumSeats end) Held
 from Flight f
 left join FlightBooking b on f.FlightID = b.FlightID
 where f.FlightID = ?) sq