我有一个有车辆制造,service_name的桌子,我需要找到最常见的车辆制造。我有一个有效的查询,但我想知道是否有更简单的方法来获得相同的结果而不创建新表。 这是我的查询
SELECT *
FROM (SELECT vehicle_make, COUNT(service_name) as num_of_services
FROM StartingTable
GROUP BY vehicle_make)
WHERE num_of_services = (SELECT MAX(num_of_services FROM (SELECT vehicle_make, COUNT(service_name) as num_of_services
FROM StartingTable
GROUP BY vehicle_make))
提前致谢
答案 0 :(得分:0)
如果您使用的是SQL Server,则可以执行以下操作:
SELECT vehicle_make, num_of_services
FROM (SELECT vehicle_make, COUNT(service_name) as num_of_services,
max(COUNT(service_name)) over () as max_num_of_services
FROM StartingTable
GROUP BY vehicle_make
) st
WHERE num_of_services = max_num_of_services;
这使用窗口函数来计算最大值。混合聚合和窗口函数起初看起来有点奇怪,但这会计算最大值 - 这正是您要查找的内容。
编辑:
如果你只想要一行,另一种方法可能更简单:
SELECT top 1 vehicle_make, COUNT(service_name) as num_of_services
FROM StartingTable
GROUP BY vehicle_make
ORDER BY COUNT(service_name) desc