简体   繁体   English

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

[英]SQL Server Averages/Sums/Groups/Counts Query Issue

I have the following table: 我有下表:

╔══════════╦════════╦═══════╦═══════╗
║ 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 ║
╚══════════╩════════╩═══════╩═══════╝

What I am trying to achieve is the following: 我想要实现的目标如下:

╔══════════╦═══════════╦═══════════════════╦═══════════════════╗
║ 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              ║
╚══════════╩═══════════╩═══════════════════╩═══════════════════╝

The game count should be the total number of games played per player and the stats should be the average per game. 游戏数应该是每个玩家玩的游戏总数,统计数据应该是每场游戏的平均数。 Basically the calculation for PlayerID 1 is the following: 基本上,PlayerID 1的计算如下:

"Stat1 Avg / Game" = (2 + 4 + 6) / 3 "Stat2 Avg / Game" = (1 + 2 + 5) / 3 “Stat1平均/游戏”=(2 + 4 + 6)/ 3“Stat2平均/游戏”=(1 + 2 + 5)/ 3

I have tried numerous variations of the same query with a combination of SUMS and COUNTS but the GameCount never comes out correct. 我已经尝试了SUMS和COUNTS组合的同一查询的多种变体,但GameCount永远不会出错。 An example of what I have tried is below 我尝试过的一个例子如下

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

So just add the DISTINCT keyword. 所以只需添加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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM