【问题标题】:can you use max in this query?你可以在这个查询中使用 max 吗?
【发布时间】:2021-05-07 00:20:09
【问题描述】:

从这张表中,我试图确定拥有最多球队数量的国家(如果国家 X 至少有一名来自 X 国家的运动员,则该国家拥有一支球队)。

driver(id,name, team, country)

此解决方案按降序恢复所有国家/地区。是否有可能确保只有拥有最多团队的一个(或多个)返回而不是全部返回?我认为您应该使用“max”命令,但我不确定。

SELECT (country) ,count(distinct team) 
FROM driver
GROUP BY country
order by count(distinct team) DESC;

【问题讨论】:

    标签: postgresql group-by max


    【解决方案1】:

    我会将您的查询用作 CTE,然后像这样从中选择 -

    WITH t AS
    ( 
     SELECT country, count(distinct team) cnt
     FROM driver
     GROUP BY country
    ) 
    SELECT country, cnt FROM t
    WHERE cnt = (SELECT max(cnt) FROM t);
    

    【讨论】:

    • 感谢您的帮助...如果不使用“WITH”,是否还有其他解决方案,或者这是唯一的方法吗?
    • 是的,通常有不止一种方法可以在 SQL 中编写某个查询。上面那句话对我来说似乎很自然,因为它与用人类语言说的大致相同——“从国家和计数列表中选择计数最高的国家”。
    【解决方案2】:

    您可以将其与窗口函数结合使用:

    with counts as (
      SELECT country, 
             count(distinct team) as num_teams,
             dense_rank() over (order by count(distinct team) desc) as rnk
      FROM driver
      GROUP BY country
    ) 
    select country, num_teams
    from counts
    where rnk = 1;
    

    如果您使用的是 Postgres 14,则可以使用 fetch first 和选项 with ties

    SELECT country, 
           count(distinct team) as num_teams
    FROM driver
    GROUP BY country
    order by count(distinct team)  desc 
    fetch first 1 rows with ties
    

    如果两个国家/地区的司机人数最多,这将返回两者。如果没有 with ties 选项(在 Postgres 14 中引入),只会返回其中一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多