SQL总数

时间:2017-03-04 02:54:57

标签: mysql sql

+--------+-------+----------+-----------+
| Maker  | Model | SeatType | NoOfSeats |
+--------+-------+----------+-----------+
| Airbus | 340   | E        |       220 |
| Airbus | 340   | F        |        20 |
| Airbus | 380   | E        |       300 |
| Airbus | 380   | F        |        60 |
| Boeing | 747   | E        |       300 |
| Boeing | 747   | F        |        40 |
| Boeing | 777   | E        |       200 |
| Boeing | 777   | F        |        20 |
| Boeing | 787   | E        |       250 |
| Boeing | 787   | F        |        25 |
+--------+-------+----------+-----------+

以下是我尝试创建此" PlaneSeats"表

select Maker, count(distinct Model)
from PlaneSeats 
group by Maker, Model 
having SUM(NoOfSeats) > 350;

这是结果查询

+--------+-----------------------+
| Maker  | count(distinct Model) |
+--------+-----------------------+
| Airbus |                     1 |
+--------+-----------------------+

但我想得到的是Maker和这个制造商制造的飞机总数,也适用于制造总座位数超过350的任何飞机的制造商。我知道计数应该是2而不是1 Maker Airbus有2种型号。请帮我找出它的错误。谢谢。

1 个答案:

答案 0 :(得分:1)

我认为你需要两个级别的聚合:

select maker, count(*)
from (select maker, model, sum(NoOfSeats) as numseats
      from planeseats ps
      group by maker, model
     ) mm
where numseats > 350
group by maker;

编辑:

当一个人足够大时,你希望所有的飞机都计入制造。这意味着将where转换为having子句:

select maker, count(*)
from (select maker, model, sum(NoOfSeats) as numseats
      from planeseats ps
      group by maker, model
     ) mm
group by maker
having max(numseats) > 350;