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

标签 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

目前我正在借助ruby之类的东西进行分组

 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?

最佳答案

使用 array_agg() 按除 contact_id 之外的所有列分组:

select 
    array_agg(contact_id) contact_ids, 
    customer_ref, full_name, email, phone,
    count(*)
from contacts
group by 2, 3, 4, 5
order by 1

 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
 {3}         |          123 | JD        | jhon@gmail.com | 1234567890     |     1
 {5}         |          123 | Jhon      | jhon@xyz.com   | no phone given |     1
(4 rows)

关于sql - 选择具有不匹配 ID 计数的不同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33196597/

相关文章:

sql - 如何根据同一表列中的值在 SQL 中进行 SELECT?

ruby-on-rails - 带有远程 : true 的 Rails link_to URL 和 HTML 选项

mysql - 如何使用数组创建 MySQL 查询?

javascript - Jquery切换菜单问题

php - 在我的情况下如何在 mysql 中定义 FOREIGN KEY 约束不起作用

SQL Server 触发器事件卡

sql - 基于值和条件的 Oracle XMLTYPE 提取

ruby-on-rails - 无法使用 json devise 注册

ruby-on-rails - 错误 : `require' : cannot load such file -- bindata (LoadError) ( using pcap_tools gem)

ruby - 如何使用 FasterCSV 更改 CSV 文件中的标题然后保存新标题?