我在MySQL表中拥有梦幻足球联赛的数据。我想查询php页面的数据。
如何创建一个查询来计算球队得分与该特定年份的联盟平均得分相比得分?
我的(简化)数据表如下所示:
游戏桌:
year | team | Week | Points
2016 | Wildcats | 1 | 44
2016 | Wildcats | 2 | 52
2015 | Hawks | 1 | 36
2015 | Hawks | 2 | 58
2016 | Hawks | 1 | 43
我如何才能找到野猫队之间的差异? 2016年平均值(48.0)和2016年所有球队的平均值(46.3)?
我可以使用此查询计算这两个数字,但不知道如何进行减法。
SELECT g1.year, g1.team, AVG(g1.points) as ppg,
(SELECT AVG(points)
FROM game AS g2
WHERE g2.year=g1.year) AS seasAvg
FROM game AS g1
GROUP BY g1.team, g1.year
ORDER BY ppg
答案 0 :(得分:1)
将整个事物包裹在外部查询中,然后您可以计算差异,同时保持简短和甜蜜。
SELECT a.*, ppg - seasAvg AS diff FROM (
SELECT g1.year, g1.team, AVG(g1.points) as ppg,
(SELECT AVG(points)
FROM game AS g2
WHERE g2.year=g1.year) AS seasAvg
FROM game AS g1
GROUP BY g1.team, g1.year
ORDER BY ppg
) AS a