如果找到目的地,我如何找到最常见的航班类型?
Table: Flight:
+-------------+---------------+
| Destination | Type |
+-------------+---------------+
| Beijing | First Class |
| Beijing | First Class |
| Beijing | First Class |
| Beijing | First Class |
| Beijing | Coach |
| London | Coach |
| London | First Class |
| London | Coach |
+-------------+---------------+
到目前为止,我所尝试的每个查询都给出了每种航班类型的总数,而不是每个目的地的最常见航班类型。
这是所需的输出:
+-------------+--------------+-------+
| Destination | Type | count |
+-------------+--------------+-------+
| Beijing | First Class | 4 |
| London | Coach | 2 |
+-------------+--------------+-------+
编辑: 所以我发现最简单的方法就是:
SELECT destination, type, count FROM Flight WHERE total=
(
SELECT MAX(total) FROM Flight fl WHERE fl.destination = Flight.destination
);
答案 0 :(得分:2)
您可以尝试GROUP BY
和HAVING
。您必须为每个组(MAX
)选择总行数为Destination, Type
的行。
SELECT Destination, `Type`, COUNT(*) AS total
FROM your_table AS aa
GROUP BY Destination, `Type`
HAVING COUNT(*) = (
SELECT MAX(each_total)
FROM (
SELECT COUNT(*) AS each_total
FROM your_table
GROUP BY Destination, `Type`
)
)
ORDER BY Destination ASC;