gpt4 book ai didi

sql - 查找任何 3 个公共(public)属性的重复记录

转载 作者:数据小太阳 更新时间:2023-10-29 07:19:44 25 4
gpt4 key购买 nike

在我的 RoR 项目中,有一个具有 10 个属性的客户模型。现在我想找到那些至少具有任何三个共同属性的客户。我怎样才能有效地进行这个查询?

可能这是一个解决方案:

Customer.select([:first_name,:last_name,:language]).
group(:first_name,:last_name,:language).having("count(*) > 1")

但是这个解决方案需要太多的组合来检查。请帮助提供更好的解决方案。

谢谢!提前。

最佳答案

这是迄今为止我能想到的最好的。也不是 SQL 解决方案。

# Arrange a 3-items combination of columns, removed id and timestamps
triplets = Customer.column_names.reject {|column| column == "id" || column == "created_at" || column == "updated_at"}.combination(3).to_a

#Group All records by same item values for each 3-items combination
all = Customer.all
res = triplets.map do|t|
all.to_a.group_by {|c| [ {t[0] => c.send(t[0].to_sym)}, { t[1] => c.send(t[1].to_sym) }, {t[2] => c.send(t[2].to_sym)} ]}
end
# removed combinations with only 1 record
final_result = res.map {|h1| h1.reject { |k, v| v.count <= 1}}

# There you have customer with 3 attributes common combinations

关于sql - 查找任何 3 个公共(public)属性的重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com