1
=======================================
Flight   SeatType   Price   GrandTotal
=======================================
F36712   Business   $480
         Economy    $375
         First      $450       ?

F12314   Business   $100
         Economy    $200
         First      $300       ?

我试过这个 SQL:

$sql = "SELECT FlightID,SeatType, sum(SeatPrice)Total
                  FROM seat 
                  WHERE SeatAvailable = 'Yes'
                  GROUP BY FlightID,SeatType, SeatPrice";

我可以知道如何计算总计(每个航班的商务舱、经济舱和头等舱的总和)吗?

4

2 回答 2

1

您的查询版本SeatPricegroup by. 这意味着您将获得每个座位价格的单独行。我假设您想获得每组的总数SeatType

SELECT FlightID,SeatType, sum(SeatPrice) as Total
FROM seat 
WHERE SeatAvailable = 'Yes'
GROUP BY FlightID, SeatType with rollup;

但是,这并没有将总计放在单独的列中。再一次,大多数版本的 SQL 都支持窗口函数来执行此操作:

SELECT FlightID,SeatType, sum(SeatPrice) as Total,
       sum(sum(SeatPrice)) over (partition by FlightId)
FROM seat 
WHERE SeatAvailable = 'Yes'
GROUP BY FlightID, SeatType;

编辑:

MySQL 不支持窗口函数。您可以对连接和聚合执行相同操作:

SELECT s.FlightID, s.SeatType, sum(s.SeatPrice) as Total, f.GrandTotal
FROM seat s join
     (select FlightId, sum(SeatPrice) as GrandTotal
      from seat
      where SeatAvailable = 'Yes'
      group by FlightId
     ) f
     on s.FlightId = f.FlightId
WHERE s.SeatAvailable = 'Yes'
GROUP BY s.FlightID, s.SeatType;
于 2013-07-28T15:53:01.873 回答
0

因为,您需要 GrandTotal 是您不能在 GROUP BY 中拥有 SeatType 的每个航班的所有商务舱、经济舱和头等舱座位的总和。

$sql = "SELECT FlightID, SUM(SeatPrice) AS Total
        FROM seat 
        WHERE SeatAvailable = 'Yes'
        GROUP BY FlightID";
于 2013-07-28T15:53:31.273 回答