GROUP_CONCAT for similar records in PostgreSQL

杀马特。学长 韩版系。学妹 提交于 2019-12-10 17:44:12

问题


I have a the following query in PostgreSQL:

SELECT sale_order.id,sale_order.name AS orden, now()::date AS hoy,
sale_order.create_date::date, split_part(res_partner.name,' ',1) AS cliente,
res_partner.email,sale_order.amount_total,res_currency.name FROM
sale_order,product_pricelist,res_currency,res_partner WHERE 
sale_order.partner_id = res_partner.id 
AND sale_order.pricelist_id = product_pricelist.id
AND product_pricelist.currency_id = res_currency.id 
AND sale_order.state = 'sent' 
ORDER BY sale_order.create_date DESC;

and the resulting set is looks like this:

658, SO658, 2015-05-17, 2015-04-16, Alejandro, some@email.com, 14272.00, MXN
654, SO654, 2015-05-17, 2015-04-15, Edgar, one@email.com, 4994.96, MXN
653, SO653, 2015-05-17, 2015-04-15, Edgar, one@email.com, 3007.29, USD

As you can see, the 2nd and 3rd records are somehow duplicated, somehow because its the same user but has different id, order name, dates, etc.

How I would like to do is disregard the dates and amounts but GROUP_CONCAT the order names, so the end result would look like this:

SO658, Alejandro, some@email.com
SO653 & SO654, Edgar, one@email.com

As you can see, I dropped the unnecessary columns and GROUP_CONCAT the order names that belongs to the same user so in the end each user would have only one record showing all their order names.

How can I do this in PostgreSQL?

Thank you!


回答1:


It is a bit hard trying out a query without table definitions or an SQL fiddle, but :

You can GROUP BY both cliente and email and then use array_agg, which will return an ARRAY. You can use string_agg(sale_order.name, ' & ') if you want really want a string, but arrays are usually easier to work with.

SELECT array_agg(sale_order.name) AS orden,
       split_part(res_partner.name,' ',1) AS cliente,
       res_partner.email
FROM  sale_order,product_pricelist,res_currency,res_partner
WHERE sale_order.partner_id = res_partner.id 
  AND sale_order.pricelist_id = product_pricelist.id
  AND product_pricelist.currency_id = res_currency.id 
  AND sale_order.state = 'sent'
GROUP BY cliente, email;


来源:https://stackoverflow.com/questions/30286435/group-concat-for-similar-records-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!