如何在ActiveRecord中每个唯一列值获取2条或更多记录?
给出:
Name | School
Jonathan | Sunshine College
Dylan | Sunshine College
Matt | Sunshine College
Joseph | Sunshine College
Stephen | Greenville School
Phil | Greenville School
Warren | Greenville School
JohnPaul | Greenville School
然后,如果我想每所学校输出 2条记录 ,它将看起来像这样:
Name | School
Jonathan | Sunshine College
Dylan | Sunshine College
Stephen | Greenville School
Phil | Greenville School
如果我希望每所学校 3条记录 ,那么它将如下所示:
Name | School
Jonathan | Sunshine College
Dylan | Sunshine College
Matt | Sunshine College
Stephen | Greenville School
Phil | Greenville School
Warren | Greenville School
答案 0 :(得分:4)
您可以按所需的列值对表的数据进行分区。之后,您可以使用条件来判断每个分区要多少条记录:
Student
.from(
Student.select('*, row_number() OVER (PARTITION BY school) AS rownum')
)
.select('*')
.where('rownum < 2')
答案 1 :(得分:1)
这是不使用sql的一种方法。
Student.group(:school)
.each{|student| Student.where(school: student.school)
.first(2)
.each{|result| puts "#{result.name.ljust(20, ' ')}| #{result.school}"}}
# Phil | Greenville School
# Warren | Greenville School
# Jonathan | Sunshine College
# Dylan | Sunshine College
答案 2 :(得分:0)
将模型的集合转换为可以比较相等性的属性列表时,可以uniq
:
MyModel.all.pluck(:first_name, :last_name).uniq