我有一张表格,其中包含动物和数字这样的字段:
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查询执行此操作? 我不知道该怎么办。
答案 0 :(得分:2)
对于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;
对于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
注意:如果有关系-每个动物的第一个查询将仅返回一行。第二个将全部返回(并列)。您没有指定在这种情况下该怎么做。
如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()
。
答案 1 :(得分:1)
您可以使用子查询来获取该信息:
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