Sort a text aggregate created with array_agg in postgresql

前端 未结 6 2091
傲寒
傲寒 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 04:57

    Although Matthew Wood's answer is better for your case, here is a way to sort arrays in PostgreSQL 8.4 and up:

    SELECT array(
        SELECT unnest(array[3,2,1]) AS x ORDER BY x
    );
    

    Knowing the array and unnest functions can be handy, since it also lets you do things like "map" over an array:

    SELECT array(
        SELECT x*x FROM (SELECT unnest(array[1,2,3]) AS x) as subquery
    );
    

    Again, this can be yours for the price of PostgreSQL 8.4 .

提交回复
热议问题