我有统计模型:
Stat(id: integer, points: float, user_id: integer, match_id: integer, team_id: integer)
对于匹配模型:
Match(id: integer, team_a_id: integer, team_b_id: integer)
Stat可以使用相同的user_id
和match_id
复制。我需要的是为每个SUM
获得点数的user_id
,然后将其除以游戏所用的match_id
数。
例:
{id: 1, points: 2, user_id: 1, match_id: 1, team_id: 1}
{id: 2, points: 3, user_id: 1, match_id: 1, team_id: 1}
{id: 3, points: 4, user_id: 1, match_id: 2, team_id: 1}
所以这里我有2场比赛。我需要得到user_id
的点数之和,然后将其除以他的游戏数量2(match_id 1和2)。然后获得前10名最高指针。
我认为您可以进一步优化查询,但这应该通过user_id加入User和Stat ang分组。
在控制器中:
@users = User.joins(:match_stats)
.group('users.id')
.select("users.name AS name, SUM(match_stats.points) as tot_points, COUNT(DISTINCT match_stats.match_id) AS tot_matches, (SUM(match_stats.points)/COUNT(DISTINCT match_stats.match_id)) AS average_points_per_match")
.order("average_points_per_match DESC")
.limit(10)
在视野中(非常基本):
<% @users.each do |user| %>
<p><%= user.name %> | <%= user.tot_points %> | <%= user.tot_matches %> | <%= user.average_points_per_match %></p>
<% end %>
要从所有统计信息中获取用户积分的总和:
user_sum_points = user.stats.map(&:points).compact.sum
我不太确定你要求的第二个号码。你打算除以用户所玩的比赛总数吗?如果是这样,那么您可以计算其匹配的唯一ID:
user_num_matches = user.stats.map(&:match_id).uniq.length
最后,做分工:
(user_sum_points / user_num_matches) unless user_num_matches == 0
我的旧代码:
stat= section
.group(:user_id)
.select("user_id, count(*) as matches_count, sum(points) as score")
.where.not(match_id: nil)
转到这个:
stat= section
.group(:user_id)
.select("user_id, COUNT(DISTINCT match_id) as matches_count, sum(points) as score")
.where.not(match_id: nil)
通过使用COUNT(DISTINCT match_id)
而不是COUNT(*)
来解决这个问题。谢谢!感谢:@Ovidiu Toma