【问题标题】:How to remove duplicates before aggregating sql如何在聚合sql之前删除重复项
【发布时间】:2021-12-26 20:17:27
【问题描述】:

我正在努力通过关系从多对多获得正确的点返回值。我有表seasonsteamsdriversresultsdriver_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 之后运行,因此它在计算期间仍然包括重复项。

【问题讨论】:

    标签: sql ruby-on-rails postgresql


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我最终解决了这个问题,只需将driver_teams.id 添加到 group by 子句中

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

      【讨论】:

        猜你喜欢
        • 2015-07-26
        • 2020-06-21
        • 2021-04-25
        • 2017-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-07
        相关资源
        最近更新 更多