将表连接到自身以显示平均值?

时间:2015-12-16 08:40:10

标签: mysql

我有各种球队和不同年份的比赛得分列表。

数据库看起来像这样:

id |team|year|week|points
1 | Wildcats|2015|1|43
2 | Wildcats|2015|2|50

我想创建一个显示,显示数据库中的每个团队,该年度得分总分以及该年度的联盟平均分数。

所以它可能看起来像:

Wildcats 2015  387  44.3

我正在尝试这个,但它不起作用:

SELECT g1.year, g1.team, xyz.total 
FROM game g1
join (SELECT avg(points) as total, year
            FROM game g2) xyz on g1.year=xyz.year
group by g1.year, g1.team

2 个答案:

答案 0 :(得分:1)

您可以使用相关子查询来获得每年的平均点数:

SELECT team, year, SUM(points) AS totalPoints,  
       (SELECT AVG(points)
        FROM game AS g2
        WHERE g2.year = g1.year) AS avgPoints
FROM game AS g1
GROUP BY team, year

Demo here

或者,加入派生表:

SELECT g1.team, g1.year, SUM(g1.points) AS totalPoints,  
       g2.avgPoints
FROM game AS g1
JOIN (SELECT AVG(points) AS avgPoints, year
      FROM game
      GROUP BY year
) AS g2 ON g1.year = g2.year
GROUP BY team, year

Demo here

答案 1 :(得分:0)

可以查询此查询:

select team,year,sum(points)as total,cast(avg(points)as decimal(10,1))  
  as average from your_table_name group by team,year