如何使用字段获取所有最大计数

时间:2013-09-27 16:19:25

标签: sql postgresql

我正在尝试返回表中包含最大条目数的名称,并返回具有最大计数的那些(名称,计数)元组的列表。我目前的解决方案使用:

select name, count(*)
from action_log
group by name
order by count desc
limit 1;

问题是使用limit 1不会考虑具有最大计数值的多个名称。

如何确定最大数量,然后获得所有匹配的名称?我想(但显然不能)做类似的事情:

select name, max(count(*))
from action_log
group by name;

5 个答案:

答案 0 :(得分:3)

SQL Fiddle

with s as (
    select name, count(*) as total
    from action_log
    group by name
), m as (
    select max(total) as max_total from s
)
select name, total
from s
where total = (select max_total from m)

答案 1 :(得分:1)

您可以使用子查询执行此操作 - 除了有一些围绕该组的规则。如何用视图简化它:

create view cname as
    select name, count(name) c
    from action_log
    group by name

然后SELECT像这样:

select distinct a.name
from action_log a
  join cname c on c.name = a.name
where c.c = (select max(c) from cname)

这是一个SQL Fiddle来证明它。

答案 2 :(得分:0)

试试这个:

select name, COUNT(*)
from action_log
group by name
HAVING COUNT(*) = (SELECT TOP 1 COUNT(*) from action_log group by name ORDER BY COUNT(*) DESC)

答案 3 :(得分:0)

您可以使用子查询

执行此操作

例如:

SELECT MAX(cnt) FROM
(SELECT name, count(*) AS cnt
FROM action_log
GROUP BY name) AS gb

答案 4 :(得分:0)

您可以使用rank()函数执行此操作,因此您不必多次查询表:

with cte as (
    select
        name, count(*) as total,
        rank() over(order by count(*) desc) as rnk
    from action_log
    group by name
)
select name, total
from cte
where rnk = 1

更好的是,你可以dense_rank(),所以你可以选择n组或参加第n组:

with cte as (
    select
        name, count(*) as total,
        dense_rank() over(order by count(*) desc) as rnk
    from action_log
    group by name
)
select name, total
from cte
where rnk <= 2 -- or rnk in (1, 2), or rnk = 2 and so on

<强> sql fiddle demo