PostgreSQL array_agg order

后端 未结 2 1908
日久生厌
日久生厌 2020-12-07 14:01

Table \'animals\':

animal_name animal_type
Tom         Cat
Jerry       Mouse
Kermit      Frog

Query:

SELECT 
array_to_strin         


        
相关标签:
2条回答
  • 2020-12-07 14:09

    Use an ORDER BY, like this example from the manual:

    SELECT array_agg(a ORDER BY b DESC) FROM table;
    
    0 讨论(0)
  • 2020-12-07 14:19

    If you are on a PostgreSQL version < 9.0 then:

    From: http://www.postgresql.org/docs/8.4/static/functions-aggregate.html

    In the current implementation, the order of the input is in principle unspecified. Supplying the input values from a sorted subquery will usually work, however. For example:

    SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;

    So in your case you would write:

    SELECT
    array_to_string(array_agg(animal_name),';') animal_names,
    array_to_string(array_agg(animal_type),';') animal_types
    FROM (SELECT animal_name, animal_type FROM animals) AS x;
    

    The input to the array_agg would then be unordered but it would be the same in both columns. And if you like you could add an ORDER BY clause to the subquery.

    0 讨论(0)
提交回复
热议问题