[英]Select multiple rows with the MAX SUM of a value grouped by another column
[英]Max() value from subquery with SUM() & multiple rows
我尝试编写一个显示子查询最大值的 mysql 查询,但我没有。 我有这个工作正常的主查询。 此查询选择每支球队在特定比赛中的总得分:
SELECT team_id, SUM(points) as totalpointsscored, game_id
FROM BOXSCORES
WHERE season="1920" and categorie=2
GROUP BY team_id, game_id
输出是这样的:
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
我想现在选择每个球队的最大值,以了解球队在哪场比赛中得分最高。 所以,输出将是:
ASM | 104 | 9117335
LEM | 128 | 9117380
STR | 102 | 9117177
我尝试使用 group by 和 have,但它不起作用。 team_id & value 没问题,但 game_id 总是第一行,而不是 game_id 附加到值。 你能帮我找到最好的解决方案吗?
在 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
在早期版本中,一种解决方案是:
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
)
我修好了它。
我只是在第一个查询中添加季节和类别,如下所示:
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.