Aggregate strings in descending order in a PostgreSQL query

a 夏天 提交于 2019-12-05 00:09:13

In PostgreSQL 9.0 or later you can order elements inside aggregate functions:

SELECT company_id, array_agg(employee ORDER BY company_id DESC)::text
FROM   tbl
GROUP  BY 1;

That's not available for PostgreSQL 8.4. You have to pre-order values to be aggregated. Use a subselect or CTE (8.4+) for this purpose:

SELECT company_id, array_agg(employee)::text
FROM  (SELECT * FROM tbl ORDER BY company_id, employee  DESC) x
GROUP  BY 1;

I order by company_id in addition, because that should speed up the aggregation.

I also use the "trick" of just casting the array to text (array_agg(employee)::text), which gives you a basic, comma-separated string without additional white space and is the fastest way.
For more sophisticated formatting, use array_to_string(array_agg(employee), ', ') like you have in your question.

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