MYSQL查找最频繁的值

时间:2018-11-12 21:00:02

标签: mysql

我有以下查询,可以正确解决租车中最常见的颜色。效果很好。

SELECT Colour
FROM car 
INNER JOIN rents
ON car.PlateNr=rents.PlateNr
GROUP BY car.colour
ORDER BY COUNT(car.colour) DESC
LIMIT 1
;

但是,如果有 2个相等的最频繁值(用于汽车颜色),第二个将丢失。如何在MYSQL中选择两个最常用的值?我在其他DBMS中看到过TOP 1值选项,​​但是我似乎在MYSQL中找不到对应的值。

1 个答案:

答案 0 :(得分:1)

您可以先计算顶部颜色计数,然后使用它来选择具有相同值的记录。

请参见SQL Fiddle

SET @top_colour_cnt = (select COUNT(car.colour) as max_color_cnt
                       from car
                       GROUP BY car.colour
                       ORDER BY COUNT(car.colour) DESC
                       LIMIT 1
                      );

SELECT @top_colour_cnt;

SELECT Colour, COUNT(car.colour)
FROM car 
GROUP BY car.colour
having COUNT(car.colour) = @top_colour_cnt
;