我有这张桌子,我需要根据序列号找到最受欢迎的租车工具。
+------------+---------------+
| hire_id | serial_number |
+------------+---------------+
| 1 | 99UU123 |
| 2 | JBB45 |
| 1 | YQE221RR |
| 3 | UTY1236Y |
| 4 | YY32RR12 |
| 4 | TRW14 |
| 5 | TRW14 |
| 6 | JBB45 |
+------------+---------------+
输出应为
+------------+---------------+
| most popular| serial_number |
+------------+---------------+
| 2 | JBB45 |
| 2 | TRW14 |
...............................
如何使用SQL命令获取此输出?
答案 0 :(得分:0)
使用Group by
和having
子句
SELECT Count(serial_number) most_popular,
serial_number
FROM tablename
GROUP BY serial_number
HAVING Count(serial_number) = (SELECT Count(serial_number) ss
FROM from tablename
GROUP BY serial_number
ORDER BY ss DESC LIMIT 1)
答案 1 :(得分:0)
以下查询将有效
SELECT COUNT(serial_number) AS `most_popular`, serial_number
FROM your_table_name
GROUP BY serial_number
ORDER BY most_popular DESC
LIMIT 2;