Aggregate strings in descending order in a PostgreSQL query

懵懂的女人 提交于 2020-01-02 00:59:13

问题


In addition to the question How to concatenate strings of a string field in a PostgreSQL 'group by' query?

How can I sort employee in descending order?

I am using PostgreSQL 8.4 which doesn't support string_agg(). I've tried to use the following, but it isn't supported:

array_to_string(array_agg(employee ORDER BY employee DESC), ',')

I'd appreciate any hint to the right answer.


回答1:


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.



来源:https://stackoverflow.com/questions/10470585/aggregate-strings-in-descending-order-in-a-postgresql-query

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