How to add order to agg row when two columns are merged

SELECT string_agg( distinct a || '-' || b , ',' ORDER BY a,b) 
FROM table;

The above sql error

ERROR: in an aggregate with DISTINCT, ORDER BY expressions should appear in the argument list

+4
source share
1 answer

For the documentation :

If DISTINCT is specified in addition to order_by_clause, then all ORDER BY expressions must match the regular arguments of the aggregate; that is, you cannot sort an expression that is not included in the DISTINCT list.

So try

select string_agg(distinct a || '-' || b, ',' order by a || '-' || b)
from a_table;

or use distinctin a view:

select string_agg(a || '-' || b , ',' order by a, b)
from (
    select distinct a, b
    from a_table
    ) s;
+3
source

Source: https://habr.com/ru/post/1660465/


All Articles