使用 SQL 聚合和计算统计数据
我有一款射击游戏,用户在一周的时间内相互竞争以积累最多的分数。我想编写一个查询来聚合镜头表中的统计数据。这里关注的表和关系是:
- user has much opportunity_competition_period
- 属于用户
- competition_period有很多镜头
- shot属于competition_period
在shots表中,我有以下字段可以使用:
- result -->;字符串值:WON、LOST 或 TIED
- amount_won -->整数值:例如-100、0、2000等。
对于每个用户,我想返回具有以下聚合统计信息的结果集:
- won_countlost_counttied_counttotal_shots_count
- total_amount_won
- ( amount_won
- (won_count+lost_count+tied_count)
- 的总和)
- avg_amount_won_per_shot( Total_amount_won /total_shots_count)
我已经工作了这个查询已经有几个小时了,但还没有取得多大进展。统计功能让我很困惑。一位朋友建议我尝试将结果返回到一个名为 shot_records 的新虚拟表中。
I have shoot 'em game where users compete against each other over the course of a week to accumulate the most points. I want to write a query that aggregates statistical data from the shots table. The tables and relationships of concern here are:
- user has many competition_periods
- competition_period belongs to user
- competition_period has many shots
- shot belongs to competition_period
In the shots table I have the following fields to work with:
- result --> string values: WON, LOST or TIED
- amount_won --> integer values: e.g., -100, 0, 2000, etc.
For each user, I want to return a result set with the following aggregated stats:
- won_count
- lost_count
- tied_count
- total_shots_count (won_count + lost_count + tied_count)
- total_amount_won (sum of amount_won)
- avg_amount_won_per_shot (total_amount_won / total_shots_count)
I've worked on this query for few hours now, but haven't made much headway. The statistical functions trip me up. A friend suggested that I try to return the results in a new virtual table called shot_records.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是基本的解决方案,计算给定球员的所有击球的统计数据(您没有指定是否希望在每个比赛周期的基础上进行统计):
请注意,这包括计算“总胜利”时的负数数字(即总数减去损失)。如果这不是您游戏的正确算法,您可以将两个地方的
SUM(Amount)
更改为SUM(IF(Amount > 0, Amount, 0))
出现在查询中。Here is the basic solution, computing the statistics across all shots for a given player (you didn't specify if you want them on a per-competition-period basis or not):
Note that this includes negatives in calculating the "total won" figure (that is, the total is decreased by losses). If that's not the correct algorithm for your game, you would change
SUM(Amount)
toSUM(IF(Amount > 0, Amount, 0))
in both places it occurs in the query.