0

我想得到行数最多的两个用户的所有行,即日志表中活动量最大的两个用户。

我只找到了下一个解决方案:首先,获取每个用户的行数,将其限制为 2:

SELECT userid, count(*) AS n_of_rows FROM my_table GROUP BY userid LIMIT 2;

然后,从我正在查询数据库的源代码(例如 Python)中,查询数据库以获取每个用户的行:

SELECT * FROM my_table where userid = $userid

考虑到 SQL 语言本身和数据库性能,它是最佳/优雅的解决方案吗?

谢谢!

4

3 回答 3

3

我认为您正在寻找的是类似的东西

select * from my_table where userid in
(select userid from my_table
 group by userid
 order by count(*) desc
 limit 2)
于 2013-09-19T20:32:00.733 回答
2

要获取行并保持顺序,请使用joinwith 聚合:

select t.*
from my_table t join
     (select userid, count(*) as cnt
      from my_table
      group by userid
      order by count(*) desc
      limit 2
     ) top2
     on t.userid = top2.userid
order by top2.cnt desc, userid;
于 2013-09-19T20:45:17.453 回答
0

尝试这个:

SELECT TOP 2 userid, count(*) AS n_of_rows 
FROM my_table 
GROUP BY userid 
ORDER BY count(*) desc
于 2013-09-19T20:29:09.483 回答