选择具有不匹配ID计数的不同元素

时间:2015-10-18 09:57:13

标签: sql ruby-on-rails ruby postgresql

我不确定我的问题是否会单独通过查询来解决,或者我需要借助脚本语言来实现这一目标

select customer_ref, full_name, email, phone from contacts where customer_ref = '123';

  contact_id  |  customer_ref  |   full_name    | email          |     phone      
  ------------+----------------+----------------+----------------+--------------
  1           |   123          | Jhon           | jhon@xyz.com   | 1234567890
  2           |   123          | Jhon Doe       | jhon@xyz.com   | 1234567890
  3           |   123          | JD             | jhon@gmail.com | 1234567890
  4           |   123          | Jhon           | jhon@xyz.com   | 1234567890
  5           |   123          | Jhon           | jhon@xyz.com   | no phone given
  6           |   123          | Jhon           | jhon@xyz.com   | 1234567890

我想要的是将匹配的信息组合在一起,如

contact_ids|customer_ref  |   full_name    | email          |     phone      | count
-----------+--------------+----------------+----------------+----------------+------
[1, 4, 6]  |   123        | Jhon           | jhon@xyz.com   | 1234567890     | 3
[2]        |   123        | Jhon Doe       | jhon@xyz.com   | 1234567890     | 1
[4]        |   123        | JD             | jhon@gmail.com | 1234567890     | 1
[5]        |   123        | Jhon           | jhon@xyz.com   | no phone given | 1

目前我正在使用像

这样的红宝石帮助进行分组
 contacts = Contact.select('full_name, email, phone').where(:customer_ref => '123')
 contacts.inject(Hash.new(0)) { |k,v| k[v] += 1; k }.map {|k,v| {:contact =>k.with_indifferent_access, :count => v }} if contacts.present?

1 个答案:

答案 0 :(得分:3)

mmap以外的所有列使用array_agg()分组:

contact_id