为什么这个查询给我错误的划分?

时间:2017-01-31 16:22:38

标签: mysql sum

我有一个查询会带回以下表格。我创建的最后一列将Total_points除以Games_played,以便在最后一列中获得Points_Per_Game数字。

这是表格

+----------+--------------+--------+-----------------+
| PlayerID | Games_Played | Points | Points_Per_Game |
+----------+--------------+--------+-----------------+
|       16 |            2 |      3 |          0.6000 |
|       20 |            2 |      3 |          0.6000 |
|       10 |            2 |      3 |          0.3750 |
|       18 |            2 |      3 |          0.3750 |
|        5 |            2 |      3 |          0.3750 |
|        9 |            2 |      3 |          0.3750 |
+----------+--------------+--------+-----------------+
6 rows in set (0.00 sec)

这是查询

SELECT Players.PlayerID, COUNT(Games.Points) AS Games_Played, 
SUM(Games.Points) AS Points, SUM(Points/Games_Played) AS Points_Per_Game
FROM Teams, Players, Games

WHERE 
Teams.PlayerID=Players.PlayerID
AND
Games.Game=Teams.Game
AND
Games.Team=Teams.Team
AND
Games.GameDate=Teams.GameDate
AND
(
CONCAT(Games.Game, '_', Games.GameDate)= 
ANY(SELECT CONCAT(Teams.Game, '_', Teams.GameDate) 
FROM Teams WHERE PlayerID='4')
AND NOT
CONCAT(Games.Game, '_', Games.Team, '_', Games.GameDate)= 
ANY(SELECT CONCAT(Teams.Game, '_', Teams.Team, '_', Teams.GameDate) 
FROM Teams WHERE PlayerID='4')

)

GROUP BY Teams.PlayerID
ORDER By Points_per_Game DESC, Points DESC, Games_Played;

是否与我正在分组并汇总所引用的列的事实有关?

我似乎无法理解为什么这不会以1.5的形式出现

1 个答案:

答案 0 :(得分:1)

...试

SELECT Players.PlayerID, COUNT(Games.Game) AS Games_Played, 
SUM(Games.Points) AS Points, SUM(Games.Points)/COUNT(Games.Game) AS Points_Per_Game
FROM Teams, Players, Games

您的Games_Played不正确或充其量是误导。

此外,我建议您考虑使用JOINS连接团队,游戏和娱乐;播放器。