簡體   English   中英

MYSQL-在具有其他列的組中顯示具有最大計數值的行

[英]MYSQL - Displaying rows with max count values in a group with other columns

我一直在搜尋,發現了類似主題的主題,但這些都不是我一直在尋找的解決方案。 在這種情況下,我有一個有效的代碼,但是對我來說似乎很hacky,應該有一個更簡單,更好的方法來完成它。

“測試”表

id
--
 1
 1
 1
 2
 2
 2
 3
 4
 4

沒什么復雜的,只是一個帶有一些重復的id值的簡單表

我想要的是將這些id分組在一起,並顯示所有重復次數最多的id ,即

id | count
----------
 1       3
 2       3

我目前想出的解決方案

select
    @max := max(count) as count
from (
    select 
        id,
        count(id) as count
    from 
        test
    group by
        id
)
as 
    inner_table;


select
    id, count
from (
    select 
        id,
        count(id) as count
    from 
        test
    group by
        id
)
as 
    inner_table
where count = @max;

一種方法用做group byhaving

select id,count(*) as cnt
from t
group by id
having count(*)=(select count(*) as cnt 
                 from t 
                 group by id
                 order by cnt desc
                 limit 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM