没有使用限制的最高出现次数

时间:2015-10-04 19:12:28

标签: sql sqlite

所以我对这个主题进行了大量搜索,并且我使用了它,因此它获得了最多的出现次数,但是我想让SQL抓取一个任意数量(如果有多个值具有最高数量)。 现在我有:

SELECT houses.cars, COUNT(houses.cars) as Numb 
FROM houses 
Group By houses.cars Order By Numb Desc 
Limit 1;

返回最高出现次数,但是例如,如果有2种类型的汽车有8次出现,我希望它返回两者。

我知道当你想要持续时间最长的值(整数)时,你就是这样做的:

SELECT times.duration AS 'Hour', 
FROM times 
WHERE times.duration >= (SELECT MAX(times.duration) 
                         FROM times);

但是无论何时我尝试用COUNT做类似的逻辑,它都会产生语法错误。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

要保持联系,您可以将having子句与子查询一起使用:

小提琴: http://www.sqlfiddle.com/#!7/ce7ec/6/0

select cars,
       count(*)
  from houses
 group by cars
having count(*) = (select max(num_occur)
                     from (select cars,
                                  count(*) as num_occur
                             from houses
                            group by cars))

如果您使用的是Oracle或SQL Server,则可以在没有子查询的情况下执行此操作:

使用Oracle 12c的这种解决方案:

select cars,
       count(*)
  from houses
 group by cars
 order by 2 desc
 fetch first 1 rows with ties;

使用SQL Server的这种解决方案:

select top(1) with ties
       cars,
       count(*)
  from houses
 group by cars
 order by 2 desc;