微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐