PostgreSQL - 选择多个最大计数

时间:2015-10-21 13:25:49

标签: postgresql select count max

我正在使用PostgreSQL 我有一个桌面竞争对手,在电子竞技游戏中提供有关竞争对手的信息。该表包含gameID,竞争对手的昵称和他/她所扮演角色的名称。

我想选择每个缺口和他们最常玩的角色 例如,如果竞争对手Faker已经玩过4次角色Ryze和Lulu 3次,我希望 Faker Ryze 4 出现在输出中。

这是我到目前为止所做的:

select nick, character, count(*) as played
from competitor
group by nick, character
order by nick;

然后我在输出中得到 Faker Ryze 4 Faker Lulu 3
我尝试过max()和嵌套,但我无法弄明白。

3 个答案:

答案 0 :(得分:2)

这样就可以了。

SELECT nick, character,played
FROM
  (SELECT s1.*,
          row_number() OVER (PARTITION BY nick
                             ORDER BY played DESC) AS row1
   FROM
     (SELECT nick, character, COUNT(*) AS played
      FROM competitor
      GROUP BY nick, character
      ORDER BY nick,
               COUNT(*) DESC) s1)s2
WHERE row1=1;

查询100%正确。 SQL小提琴here。此外,它是唯一一个可以轻松支持相同昵称关联的查询(通过row_number()更改rank())并避免不必要的JOIN

答案 1 :(得分:1)

试试这个:

with counts as (
    select nick, character, count(*) cnt, max(sometimestamp) hora
    from competitor
    group by nick, character
    order by nick, cnt desc, hora
)


select nick, character, max(cnt)
from counts c1 where nick
in (select nick from counts where nick = c1.nick limit 1)
    and character in (select character from counts where nick = c1.nick limit 1)
group by nick, character
order by nick

max(sometimestamp) hora将成为决胜局,你必须适应。或者,如果您不关心关系,请删除此字段。此查询将为您提供每个缺口的字符,具有更大的计数,如果是平局,它将返回第一个以达到最大计数。

答案 2 :(得分:0)

你使用max和nesting走正确的路线,我稍微修改了here给出的答案:

select t1.nick, t1.character, t1.count
from (
    select nick, character, count(*) as played
    from competitor
    group by nick, character
) t1
inner join
(
  select nick, max(played) max_count
  from 
  (
    select nick, character, count(*) as played
    from competitor
    group by nick, character
  )
  group by nick
) t2
  on t1.nick = t2.nick
  and t1.count = t2.max_count

如果您为基本查询创建了一个视图,那么这可能更容易阅读:

查看名为PlayerCount:

select nick, character, count(*) as played
from competitor
group by nick, character

现在SQL查询:

select t1.nick, t1.character, t1.count
from PlayerCount t1
inner join
(
  select nick, max(played) max_count
  from PlayerCount
  group by nick
) t2
on t1.nick = t2.nick
and t1.count = t2.max_count