2016-11-11 120 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;