我有下表:
╔══════════╦════════╦═══════╦═══════╗ ║ PlayerID ║ GameID ║ Stat1 ║ Stat2 ║ ╠══════════╬════════╬═══════╬═══════╣ ║ 1 ║ A ║ 2 ║ 1 ║ ║ 1 ║ B ║ 4 ║ 2 ║ ║ 1 ║ C ║ 6 ║ 5 ║ ║ 2 ║ A ║ 2 ║ 4 ║ ║ 2 ║ B ║ 2 ║ 6 ║ ║ 2 ║ C ║ 2 ║ 8 ║ ║ 2 ║ D ║ 4 ║ 2 ║ ║ 2 ║ E ║ 6 ║ 1 ║ ║ 3 ║ A ║ 5 ║ 9 ║ ║ 3 ║ G ║ 6 ║ 4 ║ ║ 3 ║ 高 ║ 4 ║ 2 ║ ║ 3 ║ N ║ 8 ║ 6 ║ ╚══════════╩════════╩═══════╩═══════╝
我想要达到的目标如下:
╔══════════╦═══════════╦═══════════════════╦══════ ═════════════╗ ║ PlayerID ║ GameCount ║ Stat 1 Avg / Game ║ Stat 2 Avg / Game ║ ╠══════════╬═══════════╬═══════════════════╬══════ ═════════════╣ ║ 1 ║ 3 ║ 4 ║ 2.66 ║ ║ 2 ║ 5 ║ 3.2 ║ 4.2 ║ ║ 3 ║ 4 ║ 5.75 ║ 5.25 ║ ╚══════════╩═══════════╩═══════════════════╩══════ ═════════════╝
游戏计数应该是每个玩家玩的游戏总数,而统计数据应该是每场比赛的平均数。基本上 PlayerID 1 的计算如下:
“Stat1 平均 / 游戏” = (2 + 4 + 6) / 3 “Stat2 平均 / 游戏” = (1 + 2 + 5) / 3
我已经尝试了使用 SUMS 和 COUNTS 组合的同一查询的多种变体,但 GameCount 永远不会正确。我尝试过的一个例子如下
SELECT PlayerID,
COUNT(GameID) AS GameCount,
SUM(Stat1) / COUNT(GameID) "Stat 1 Avg / Game",
SUM(Stat2) / COUNT(GameID) "Stat 2 Avg / Game"
FROM PublishedStats A
GROUP BY PlayerID
SELECT PlayerID,
COUNT(GameID) OVER (PARTITION BY PlayerID) AS GameCount,
SUM(Stat1) / COUNT(GameID) OVER (PARTITION BY PlayerID) "Stat 1 Avg / Game",
SUM(Stat2) / COUNT(GameID) OVER (PARTITION BY PlayerID) "Stat 2 Avg / Game",
FROM Stats
GROUP BY PlayerID, GameID