如何调整此查询以显示每个游戏的平均目标,而不是总得分?

时间:2016-12-24 15:06:35

标签: mysql

我有以下查询:

select u.user_name, sum(goals) 
from ((select player1_id as player, player1_goals as goals from results       
where community_id = 16 ) 
union all (select player2_id as player, player2_goals as goals from     
results where community_id = 16 ) ) p 
join users u on p.player = u.id 
group by player order by sum(goals) 

产生如下结果:

+----------+------------+
| user_name| sum(goals) |
+----------+------------+
| Player 1 |    9       |
| Player 2 |    7       |
| Player 3 |    4       |
+----------+------------+

此查询基于以下内容:

results表:

+---------------+
| results_id    |
| community_id  | 
| player1_id    | 
| player1_goals | 
| player2_id    | 
| player2_goals |
+---------------+

users表:

+---------+
|   id    |
+---------+
|user_name|
+---------+

我的问题如下:

查询表中的每个玩家都玩过不同数量的游戏,所以我不想显示每个玩家得分的目标数,而是想显示每场比赛的平均进球数。

我想要的输出是:

+----------+-----------+-----------------+
| user_name| sum(goals) | goals per game |
+----------+------------+----------------+
| Player 1 |    9       |       1.3      |
| Player 2 |    7       |       0.9      |
| Player 3 |    4       |       0.4      |
+----------+------------+----------------+

如何调整初始查询以显示每场比赛的平均目标,而不仅仅是得分?

1 个答案:

答案 0 :(得分:0)

试试这个:

select u.user_name,
    sum(r.goals) total_goals,
round(  sum(r.goals)/count(1), 2) avg_goals
from (select
    community_id,
    player1_id id,
    player1_goals goals
from results
union all
select
    community_id,
    player2_id,
    player2_goals
from results) r
inner join users u
on r.id = u.id
where r.community_id = 16
group by r.id, u.user_name
order by avg_goals desc;