简体   繁体   English

sql中的sum语句

[英]sum statement in sql

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

F12314   Business   $100
         Economy    $200
         First      $300       ?

I've tried this SQL: 我试过这个SQL:

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

May I know how can I calculate the grand total (sum of the business, economy and first class for each flight)? 我能否知道如何计算总计(每次航班的业务,经济和头等舱的总和)?

Your version of the query has SeatPrice in the group by . 您的查询版本在group by SeatPrice中具有SeatPrice This means that you are getting a separate row for each seat price. 这意味着您将获得每个座位价格的单独一行。 I assume you want to get the total in each group of SeatType : 我假设您想获取每个SeatType组的SeatType

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

However, that does not put the grand total in a separate column. 但是,这并未将总计放在单独的列中。 Once again, most versions of SQL support window functions to do this: 再次,大多数版本的SQL支持窗口都可以执行此操作:

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

EDIT: 编辑:

MySQL does not support window functions. MySQL不支持窗口功能。 You can do the same with a join and aggregation: 您可以对联接和聚合执行相同的操作:

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;

Since, you need the GrandTotal to be the Sum of all the business, economy and first class seats for each flight you can't have SeatType in the GROUP BY. 既然如此,您需要将GrandTotal设为您无法在GROUP BY中使用SeatType的每个航班的所有商务,经济舱和头等舱座位的总和。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM