=======================================
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";
我是否知道如何计算总计(每次航班的商业,经济和头等舱的总和)?
答案 0 :(得分:1)
您的查询版本SeatPrice
中有group 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;
答案 1 :(得分:0)
因为,您需要Grand Total为每个航班的所有商务舱,经济舱和头等舱座位的总和,您不能在GROUP BY中拥有座位类型。
$sql = "SELECT FlightID, SUM(SeatPrice) AS Total
FROM seat
WHERE SeatAvailable = 'Yes'
GROUP BY FlightID";