如何基于多个字段对行进行分组?

时间:2013-10-10 16:03:39

标签: ruby-on-rails postgresql

我有一个notifications表,我根据他们选择的频率将报告通过电子邮件发送给用户。

如果某个电子邮件地址存在多个questions并且具有相同的frequency ...那么我需要将它们组合在一起,以便我可以针对这两个问题发送一份报告。

[
   #<Notification id: 1, question_id: 58, email: "john@example.com", frequency: "daily">, 
   #<Notification id: 2, question_id: 25, email: "john@example.com", frequency: "daily">,
   #<Notification id: 3, question_id: 47, email: "john@example.com", frequency: "monthly">,
   #<Notification id: 3, question_id: 19, email: "frank@example.org", frequency: "monthly">
] 

因此,在我的示例数据中,将发送3个报告:

  • 1到john@example.com每日问题58和25
  • 每月
  • 1到john@example.com查询问题47
  • 1到frank@example.org,每月一次问题19

我可能不会很好地解释这一点,所以如果需要澄清,请告诉我。

1 个答案:

答案 0 :(得分:1)

您可以使用常规的group_by:

来实现此目的
@notifications = your_method_to_retrieve_notifications
@notifications = @noticications.group_by do |notif|
  notif.ferquency + ':' + notif.email
end

这会将您的通知分组如下:

@notifications = {
  'daily:john@example.com' => [<Notification id: 1>, #etc.],
  'monthly:john@example.com' => [# list of notifications],
  'monthly:frank@example.org' => [# list of notif]
}

如果您只想要一组按频率和频率分组的通知列表电子邮件,使用上述方法并添加:

@notifications = your_method_to_retrieve_notifications
@notifications = @noticications.group_by do |notif|
  notif.ferquency + ':' + notif.email
end.values
# returns Array of arrays like:
[
  [<Notification id: 1 frequency: "daily", email "a@b.com">,<Notification id: 2 frequency: "daily", email "a@b.com">],
  [<Notification id: 3 frequency: "daily", email "xx@yy.com">],
  [<Notification id: 4 frequency: "monthly", email "a@b.com">,<Notification id: 5 frequency: "monthly", email "a@b.com">],
]