问题
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