SQL - 基于减去多行显示可用席位

时间:2017-04-28 11:53:47

标签: sql postgresql

我一直试图写一个查询,从几张表中检索航班信息和座位预订,我的目的是显示已取消(' C'),保留(&#39)的航班详细信息; R')和可用座位数。我已经设法获取取消和预留座位的详细信息,但我正在努力计算基于此的座位。似乎因为有两行,行重置座位数而不是正确计算它。我的代码在

之下
SELECT f.FlightID, f.FlightDate, fb.Status, sum(numseats) AS 
NumberOfTotalSeats, maxcapacity - sum(numseats) AS NumberOfAvailiableSeats
FROM Flight f
INNER JOIN FlightBooking fb ON f.FlightID = fb.FlightID
WHERE (f.flightID = 5 AND fb.status = 'R') OR (f.flightID = 5 AND fb.status 
= 'C')
GROUP BY f.FlightID, fb.status

目前返回以下内容:

FlightID, FlightDate,         Status, NumberOfTotalSeats, NumberOfAvailableSeats

   5, 2017-04-07 00:00:00,     C,                 10,                    490
   5 ,2017-04-07 00:00:00,     R,                  2,                    498

我希望NumberOfAvailableSeats列为每个列显示488,并编辑我的查询以允许此操作。我正在使用PostgreSQL 9.6

提前致谢!

1 个答案:

答案 0 :(得分:0)

您希望SUM OVER两个状态总和:

SELECT 
  f.FlightID, 
  f.FlightDate, 
  fb.Status, 
  sum(fb.numseats) AS NumberOfTotalSeats, 
  f.maxcapacity - sum(sum(fb.numseats)) over (partition by f.FlightID)
    AS NumberOfAvailiableSeats
FROM Flight f
INNER JOIN FlightBooking fb ON f.FlightID = fb.FlightID
WHERE f.flightID = 5 AND fb.status IN ('R','C') 
GROUP BY f.FlightID, fb.status;

然而,正如poz所提到的,用一行来阅读会更容易:

SELECT 
  f.FlightID, 
  f.FlightDate,
  f.maxcapacity,
  sum(case when fb.Status = 'R' then fb.numseats else 0 end) as reserved,
  sum(case when fb.Status = 'C' then fb.numseats else 0 end) as cancelled,
  f.maxcapacity - sum(fb.numseats) AS NumberOfAvailiableSeats
FROM Flight f
INNER JOIN FlightBooking fb ON f.FlightID = fb.FlightID
WHERE f.flightID = 5 AND fb.status IN ('R','C') 
GROUP BY f.FlightID;

正如pozs在另一个问题中提出的那样:减去所有预留和取消席位是否有意义?所以取消会像预订一样阻止座位吗?也许你必须调整算法甚至数据模型。