简体   繁体   English

来自带有 SUM() 和多行的子查询的 Max() 值

[英]Max() value from subquery with SUM() & multiple rows

I try to write a mysql query that display max value of a sub query but I don't.我尝试编写一个显示子查询最大值的 mysql 查询,但我没有。 I have this primary query that works fine.我有这个工作正常的主查询。 This query select total points scored by each team for a specific game :此查询选择每支球队在特定比赛中的总得分:

SELECT team_id, SUM(points) as totalpointsscored, game_id 
FROM BOXSCORES 
WHERE season="1920" and categorie=2 
GROUP BY team_id, game_id

Output is like this :输出是这样的:

team_id | value (points scored) | game_id
    ASM |                    98 | 9117338
    ASM |                   104 | 9117335
    ASM |                    75 | 9117324
    LEM |                   128 | 9117380
    LEM |                    97 | 9117316
    STR |                    95 | 9117334
    STR |                   102 | 9117177
    STR |                    88 | 9117469

I'd like to select now the max value for each team to know in what game a team scored the most.我想现在选择每个球队的最大值,以了解球队在哪场比赛中得分最高。 So, the output would be :所以,输出将是:

ASM | 104 | 9117335
LEM | 128 | 9117380
STR | 102 | 9117177

I try with group by and having but it doesn't work.我尝试使用 group by 和 have,但它不起作用。 team_id & value is ok but the game_id is always the first row & not the game_id attach to the value. team_id & value 没问题,但 game_id 总是第一行,而不是 game_id 附加到值。 Could you help me to find the best solution?你能帮我找到最好的解决方案吗?

In MySQL 8.0, you can use window functions:在 MySQL 8.0 中,您可以使用窗口函数:

select *
from (
    select 
        team_id, 
        sum(points) as total_points_scored, 
        game_id,
        rank() over(partition by team_id order by sum(points) desc) rn
    from boxscores
    where season = '1920' and categorie = 2 
    group by team_id, game_id
) t
where rn = 1

In earlier versions, one solution is:在早期版本中,一种解决方案是:

select 
    team_id, 
    sum(points) as total_points_scored, 
    game_id
from boxscores b
where season = '1920' and categorie = 2 
group by team_id, game_id
having sum(points) = (
    select sum(points) 
    from boxscore b1
    where b1.season = b.season and b1.categorie = b.categorie and b1.team_id = b.team_id
    group by game_id
    order by sum(points) desc
    limit 1
)

I fixed it.我修好了它。

I just add season & categorie in first query like this :我只是在第一个查询中添加季节和类别,如下所示:

select 
    team_id, 
    sum(points) as total_points_scored, 
    game_id, season, categorie
from BOXSCORES b
where season= '1920' and categorie = 2 
group by team_id, game_id
having sum(points) = (
    select sum(points) 
    from BOXSCORES b1
    where b1.season= b.season and b1.categorie = b.categorie and b1.team_id= b.team_id
    group by game_id
    order by sum(points) desc
    limit 1
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM