首页 > 解决方案 > 如何在聚合sql之前删除重复项

问题描述

我正在努力通过关系从多对多获得正确的积分返回值。我有表格seasons, teams, drivers,resultsdriver_teams下面的关系

class Season < ApplicationRecord
  has_many :driver_teams
  has_many :drivers, through: :driver_teams
  has_many :teams, through: :driver_teams
end

class DriverTeam < ApplicationRecord
  belongs_to :season
  belongs_to :driver
  belongs_to :team

  has_many :results
end

class Team < ApplicationRecord
  has_many :driver_teams
  has_many :results, through: :driver_teams
end

class Driver < ApplicationRecord
  has_many :driver_teams
  has_many :results, through: :driver_teams
end

class Result < ApplicationRecord
  belongs_to :driver_team
  has_one :driver, though: :driver_team
  has_one :team, though: :driver_team
end

results表有一个 points 属性,它只是一个简单的整数字段我试图获得一个赛季内每个团队的所有点的总和,如下所示

season.teams.joins(:results).select('teams.*, SUM(results.points) AS points').group('teams.id')

但是因为一个团队可以有多个使用Driverteam直通表的车手,所以这些积分被每支车队的车手数量重复,因为teams从一个赛季中引用将返回直通表中的多个车队。

理想的结果是在season.teams一个赛季中只返回每支球队的单个实例。

有没有办法season.teams在运行聚合 SQL 函数之前防止返回团队的重复项?我尝试过简单地使用 season.teams.distinct,但不同的语句似乎在 group by 之后运行,因此它仍然包括计算期间的重复项。

标签: sqlruby-on-railspostgresql

解决方案


也许尝试选择之前的不同,不要使用.distinctruby的功能。做类似的事情(Select distinct seasons FROM..)。它应该让你没有重复。


推荐阅读