SQL Server平均值/总和/组/计数查询问题

时间:2013-05-15 22:15:27

标签: sql sql-server-2008 group-by average

我有下表:

╔══════════╦════════╦═══════╦═══════╗
║ 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 ║ H      ║     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 Avg / Game”=(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

1 个答案:

答案 0 :(得分:0)

所以只需添加DISTINCT关键字。

SELECT PlayerID, 
COUNT(DISTINCT GameID) AS GameCount, 
AVG(Stat1)  "Stat 1 Avg / Game",
AVG(Stat2)  "Stat 2 Avg / Game"
FROM PublishedStats A
GROUP BY PlayerID