连接表的平均值

时间:2017-05-21 20:02:08

标签: mysql sql

我有一个问题:

SELECT p.NAME, r.DATE, c.NAME, SUM(hs.result), SUM(h.par), (SUM(hs.result) - SUM(h.par)) AS "Score"
 FROM hole_scores hs
 JOIN players p ON hs.player_id = p.id
 JOIN rounds r ON r.id = hs.session_id
 JOIN holes h ON h.id = hs.hole_id 
 JOIN courses c ON c.id = r.course_id
 GROUP BY p.NAME, r.id
 ORDER BY Score ASC

查询给出了这个结果(第一行):

 NAME       DATE        NAME        SUM(hs.result)  SUM(h.par)  Score
Player 1    29.7.2014   Course 1    50              57          -7
Player 2    7.6.2014    Course 2    48              54          -6
Player 1    22.5.2014   Course 1    51              57          -6
Player 3    6.6.2014    Course 1    52              57          -5
Player 1    19.8.2013   Course 1    53              57          -4
Player 4    1.9.2011    Course 1    56              59          -3
Player 5    15.10.2011  Course 1    56              59          -3
Player 4    2.8.2013    Course 1    54              57          -3
Player 1    3.6.2014    Course 1    54              57          -3
Player 6    8.7.2014    Course 1    54              57          -3
Player 4    16.7.2014   Course 1    54              57          -3
Player 1    21.4.2015   Course 1    53              56          -3
Player 2    23.6.2012   Course 2    52              54          -2

我如何获得每位球员的平均得分?

2 个答案:

答案 0 :(得分:1)

请尝试以下方法......

SELECT players.id AS player_id,
       players.name AS player_name,
       AVG( Score ) AS avg_score
FROM ( SELECT hole_scores.player_id AS player_id,
              ( SUM( hole_scores.result ) - SUM( holes.par ) ) AS Score
       FROM hole_scores
       JOIN holes ON holes.id = hole_scores.hole_id
       JOIN rounds ON rounds.id = hole_scores.session_id
       GROUP BY hole_scores.player_id,
                rounds.id
     ) AS scoreFinder
JOIN players ON players.id = scoreFinder.player_id
GROUP BY players.id
ORDER BY player_name,
         player_id;

此语句使用基于所提供语句的简化版本的子查询来查找每个 player的每个round 的分数。

请注意,通常name通常不会被认为是唯一的,因为它通常是可能的,即使通常不是这样,两个players 可以具有相同的name。因此,我选择id值来唯一标识每个player。由于此值可以在hole_scores.player_id中找到,因此无需在此阶段加入players

然后,它会在子查询的结果与INNER JOIN之间执行players,以便每个name的{​​{1}}可以包含在结果中。我选择在此阶段而不是在子查询中加入player,因为子查询的结果只有一个记录,每个players要加入,而不是可能很多对于子查询的源数据集中的每个玩家。我希望这会使声明略微提高效率。

然后,语句按照每个玩家的唯一标识符对连接数据集的记录进行分组,并返回每个player的{​​{1}}和id值及其name的平均值。 1}}在每个player的末尾。

如果您有任何问题或意见,请随时发表评论。

答案 1 :(得分:0)

如果你想要平均值,我认为你可以做到:

SELECT p.NAME, (SUM(hs.result) - SUM(h.par))/COUNT(*) AS "Score"
FROM hole_scores hs JOIN
     players p
     ON hs.player_id = p.id JOIN
     rounds r
     ON r.id = hs.session_id JOIN
     holes h
     ON h.id = hs.hole_id JOIN
     courses c
     ON c.id = r.course_id
GROUP BY p.NAME
ORDER BY Score ASC