Sort a text aggregate created with array_agg in postgresql

前端 未结 6 2093
傲寒
傲寒 2021-02-05 04:42

I have a table in postgresql. The following table \"animals\" will do to explain my problem:

name
------
tiger
cat
dog

Now I am using the follo

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 05:21

    For modern PostgreSQL (since version 9.0), you can use an ORDER BY clause in an aggregate expression:

    SELECT
        array_to_string(array_agg(name ORDER BY name), ', ')
    FROM
        animals;
    

    Also, for your specific purpose, you can use string_agg to simplify your query:

    SELECT
        string_agg(name, ', ' ORDER BY name)
    FROM
        animals;
    

提交回复
热议问题