为什么 max function 和 group by 在 SQL 中不能很好地协同工作?

Why don't max function and group by work well together in SQL?

我创建了一个 Match table 并想要 运行 这个查询:

select player_id, max(goals)
from soccer.player_match_stat
group by player_id

目标是找到 player_id 在这个 table 中进球数最多的人。所以,我将 tables 数据按 player_id 分组,然后得到 max() 的目标,但结果不正确!

匹配:

player_id goals
1 2
2 5
1 4

预期结果:

player_id goals
1 6

如果你能帮我解决这个问题,我将不胜感激:)

可能您需要的聚合不是 max 而是 sum:

select player_id, sum(goals)
from soccer.player_match_stat
group by player_id
order by 2 desc
limit 1

如果您按 max 汇总,您只会获得每场比赛的球员进球的最大值。 如果按 sum 汇总,您将获得所有游戏中玩家的总进球数。正如我从问题中了解到的那样,您必须计算目标总数(6 玩家 1 的目标)。

尝试以下操作:

CREATE TABLE Match_tbl(
player_id int,  
goals int             );

INSERT INTO Match_tbl values    
                      (1,2),
                      (2,5),
                      (1,4);

在 MySQL 或 PostgreSQL 中:

  SELECT player_id
     , total_goals
  FROM (
     SELECT player_id
          , sum(goals) as total_goals
     FROM Match_tbl
     GROUP BY player_id
 ) as t1
  ORDER BY total_goals DESC
 LIMIT 1
    

https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/180

SQL 服务器:

 SELECT  TOP 1  player_id
      , sum(goals) as total_goals
 FROM Match_tbl
 GROUP BY player_id
 ORDER BY total_goals DESC

演示:https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=614d8063d98d4655fece19b6ac9f0faa

Result:

player_id total_goals
1            6