2016-11-11 123 views
4
SELECT string_agg(distinct a || '-' || b , ',' ORDER BY a,b) 
FROM table; 

上面的SQL给错误如何在字符串AGG添加顺序,当两列串接

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

+0

Postgres您使用的是哪个版本? –

+0

我正在使用PostgreSQL 9.6 – user2724990

+0

请显示您的表格结构。你是否打算在查询中做任何分组? –

回答

3

对于the documentation

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

所以尽量

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

或在导出的t中使用distinct能够:

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