2

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

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

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

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

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

5 回答 5

3

SQL小提琴

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)
于 2013-09-27T16:51:04.123 回答
1

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

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来证明它。

于 2013-09-27T16:42:59.443 回答
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

于 2013-09-27T17:43:49.653 回答
0

您可以使用子查询来做到这一点

例如:

SELECT MAX(cnt) FROM
(SELECT name, count(*) AS cnt
FROM action_log
GROUP BY name) AS gb
于 2013-09-27T17:00:22.837 回答
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)
于 2013-09-27T16:40:56.200 回答