postgresql – 当串联两列时,如何在字符串agg中添加顺序

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

上面的sql给出了错误

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

解决方法

对于 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;

或在派生表中使用distinct:

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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...