简体   繁体   English

如何选择最大计数的行进行分组

[英]How do I select a row with max count doing a group by

I have a table posts with columns ( id , user_name , thread_id ). 我有一个表posts列( iduser_namethread_id )。
A user can submit multiple posts for a thread. 用户可以为一个线程提交多个帖子。 thread to post is one to many. 发布线程是一对多的。

I need to find out who submitted max posts per thread. 我需要找出谁每个线程最多提交了帖子。 So the result would be Max(Count) , user_name , thread_id WHERE there will be only one row per thread_id. 因此结果将是Max(Count)user_namethread_id ,其中每个thread_id只有一行。

The table is too huge so I wanted to get the query optimized as much as I could. 该表太大,因此我想尽可能优化查询。

You can try with the group by and having clauses: 您可以group by having子句来尝试使用该group by

select t.user_name, t.thread_id , count(*) as max_count
from tbl t
group by t.user_name, t.thread_id
having count(*) = ( select count(*) as ttl
                    from tbl
                    where thread_id = t.thread_id
                    group by user_name
                    order by ttl desc
                    limit 1 )
select user_name, thread_id, count(*) as max
from tbl t
group by user_name, thread_id
having count(*) = (
    select count(*) as cnt /* most posts per user per thread */
    from tbl
    group by user_name, thread_id
    order by cnt desc
    limit 1
)

Easy workaround for system that don't have limit is: 对于没有limit系统,简单的解决方法是:

select user_name, thread_id, count(*) as max
from tbl t
group by user_name, thread_id
having count(*) = (
    select max(cnt) from (
        select count(*) as cnt /* most posts per user per thread */
        from tbl
        group by user_name, thread_id
    ) m
)

Try this.. SELECT p.user_name, p.thread_id FROM post p GROUP BY p.user_name,p.thread_id HAVING COUNT(p.thread_id) = (SELECT MAX(threadtypecount) FROM (SELECT thread_id, COUNT([user_name]) AS threadtypecount FROM post GROUP BY thread_id) T1) 试试这个。.选择p.user_name,p.thread_id FROM post p GROUP BY p.user_name,p.thread_id HAVING COUNT(p.thread_id)=(SELECT MAX(threadtypecount)FROM(SELECT thread_id,COUNT([user_name])AS从发帖组(thread_id)发出的threadtypecount)T1)

hope this helps.. 希望这可以帮助..

Suppose you have a table posts with fields id , user_name & thread_id . 假设您有一个表posts其中包含字段iduser_namethread_id If you want to query which user has posted the most posts on a specific thread and the total number of his posts from a table, you can achieve that with this MySQL query: 如果要查询哪个用户在特定线程上发布的帖子最多,以及从表中发布的帖子总数,则可以通过以下MySQL查询来实现:

SELECT user_name, thread_id, count(thread_id) 
FROM posts WHERE thread_id=1 GROUP BY user_name 
ORDER BY count(thread_id) DESC LIMIT 1;

It will return only one row... 它只会返回一行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM