【问题标题】:Get the most common value in mysql获取mysql中最常用的值
【发布时间】:2019-04-01 17:50:56
【问题描述】:

我有一个表格,其中包含 animalnumber 字段,如下所示:

    Horse   1
    Mouse   2
    Cat     2
    Horse   4
    Cat     2
    Mouse   1
    Horse   1
    Horse   3
    Mouse   2
    Cat     1

现在我想获得每种动物最常见的价值。 所以我期待这个结果:

Horse   1
Mouse   2
Cat     2

是否可以使用一个 mySQL 查询来做到这一点? 我不知道我该怎么做。

【问题讨论】:

  • 重复引用只返回一行(LIMIT 1)。这个问题不一样。
  • 你的Mysql版本是多少?以及您希望如何处理关系?
  • @ThomasG - 1 是“马”最常见的number

标签: mysql


【解决方案1】:

对于 8.0 之前的版本:

select distinct a.animal, (
  select b.number
  from animals b
  where b.animal = a.animal
  group by b.animal, b.number
  order by count(*) desc
  limit 1
) as number
from animals a;

Demo

使用 MySQL 8.0(或 MariaDB 10.2):

with count_all as (
  select animal, number, count(*) as cnt
  from animals
  group by animal, number
), count_max as (
  select animal, max(cnt) as cnt
  from count_all
  group by animal
)
select animal, number
from count_all
natural join count_max

Demo

注意:如果存在平局 - 第一个查询将只返回每只动物一行。第二个将它们全部返回(并列行)。您没有指定在这种情况下该怎么做。

正如 Juan Carlos Oropeza 所指出的 - 在 MySQL 8 中,您还可以使用窗口函数 ROW_NUMBER()RANK()

with count_all as (
  select animal, number, count(*) as cnt
  from animals
  group by animal, number
), count_max as (
  select animal, number,
    row_number() over (partition by animal order by cnt desc) as rn
  from count_all
)
select animal, number
from count_max
where rn = 1

这不会返回平局。如果您想获得并列的行,只需将 row_number() 替换为 rank()

【讨论】:

  • 使用 mysql 8,您可以使用 row_number 或 rank。
  • @JuanCarlosOropeza - 我一开始以为代码太多 :-) - 但在您发表评论后,我意识到它更灵活。
【解决方案2】:

您可以使用子查询来获得:

SELECT c.animal,MAX(c.cnt)
FROM (
  SELECT t.animal, t.number, count(*) AS cnt
  FROM your_table t
  GROUP BY t.animal, t.number) c
GROUP BY c.animal

【讨论】:

  • MAX(c.cnt) 不是最常见的 number
  • 误解了问题,抱歉
  • 没关系。 OP 似乎不太关心正确的结果。
猜你喜欢
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2020-08-20
  • 1970-01-01
  • 2015-01-23
  • 2021-06-02
相关资源
最近更新 更多