sql - 如何在聚合sql之前删除重复项
问题描述
我正在努力通过关系从多对多获得正确的积分返回值。我有表格seasons
, teams
, drivers
,results
和driver_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 之后运行,因此它仍然包括计算期间的重复项。
解决方案
也许尝试选择之前的不同,不要使用.distinct
ruby的功能。做类似的事情(Select distinct seasons FROM..)
。它应该让你没有重复。
推荐阅读
- python - 想要使用 bash 或 python 创建 n-1 级别的目录列表(不包含任何子文件夹的文件夹)
- javascript - Transform 属性在 Firefox 中不起作用,但在 Chrome 和 Safari 中起作用。该怎么办?
- angular - Angular - 使用 ngOnInit 加载组件
- c# - C#通过按下按钮在后台执行
- websphere - MQ 队列管理器别名
- reactjs - 如何将 Material-ui App Bar 添加到类组件?
- swift - 如何在 Swift 中裁剪 UIImage 以进行遮罩
- ruby-on-rails - 查找具有至少一个关联的记录,但排除任何关联匹配条件的记录
- java - 如何在数据库JAVA中建立两个对象之间的关系
- .net - 从 C++/CLI 程序集创建 AnyCPU-only 元数据程序集