SQL-如何随着时间的推移对客户端数据求和?

时间:2017-04-25 22:14:04

标签: sql sql-server tsql

目标:多个日期/交易的SUM / AVG客户数据。 详细问题:如何正确分组客户端(' PlayerID')然后SUM整个int(MinsPlayed),然后是AVG(AvgBet)? 当前问题:我的结果是在90天内逐日提供个别交易,而不是在90天内提供SUM / AVG。

Current Script/Results: FirstName-Riley is showing each individual daily transaction instead of 1 total SUM/AVG over set time period

2 个答案:

答案 0 :(得分:0)

首先,您不需要使用DISTINCT,因为您将使用GROUP BY聚合结果,因此您可以将其取出。

您为每个事务返回一行的原因是您的GROUP BY子句包含您尝试聚合的列(例如TimePlayed)。通常,您只希望GROUP BY not 聚合的列,因此从使用SUM或AVG(TimePlayed,PlayerSkill等)聚合的GROUP BY子句中删除所有列。

答案 1 :(得分:0)

这是您当前的SQL:

SELECT DISTINCT CDS_StatDetail.PlayerID, 
    StatType,
    FirstName,
    LastName,
    Email,
    SUM(TimePlayed)/60 AS MinsPlayed,
    SUM(CashIn) AS AvgBet,
    SUM(PlayerSkill) AS AvgSkillRating,
    SUM(PlayerSpeed) AS Speed,
    CustomFlag1
FROM CDS_Player INNER JOIN CDS_StatDetail
ON CDS_Player.Player_ID = CDS_StatDetail.PlayerID
WHERE StatType='PIT' AND CDS_StatDetail.GamingDate >= '1/02/17' and CDS_StatDetail.GamingDate <= '4/02/2017' AND CustomFlag1='N'
GROUP BY CDS_StatDetail.PlayerID, StatType, FirstName, LastName, Email, TimePlayed, CashIn, PlayerSkill, PlayerSpeed, CustomFlag1
ORDER BY CDS_StatDetail.PlayerID

你想要这样的东西:

SELECT CDS_StatDetail.PlayerID, 
    SUM(TimePlayed)/60 AS MinsPlayed,
    AVG(CashIn) AS AvgBet,
    AVG(PlayerSkill) AS AvgSkillRating,
    SUM(PlayerSpeed) AS Speed,
FROM CDS_Player INNER JOIN CDS_StatDetail
ON CDS_Player.Player_ID = CDS_StatDetail.PlayerID
WHERE StatType='PIT' AND CDS_StatDetail.GamingDate BETWEEN '2017-01-02' AND '2017-04-02' AND CustomFlag1='N'
GROUP BY CDS_StatDetail.PlayerID

下次请复制并粘贴文字,而不仅仅是链接到屏幕截图。