在PostgreSQL中使用string_agg和distinct时出现问题

34

我在下面的查询中遇到了错误。基本上是想要同时使用||distinct

select string_agg( 'pre' || distinct user.col, 'post')

这样做很好

select string_agg( 'pre' || user.col, 'post')

& 这个

select string_agg(distinct user.col, 'post')
3个回答

59
select string_agg(distinct 'pre' || user.col, 'post')

由于上述操作会阻止在distinct聚合中使用索引,因此请去掉'pre'

select 'pre' || string_agg(distinct user.col, 'postpre')

2
这将在整个string_agg输出中添加一个单独的“pre”字符串,例如preFIRSTpostSECONDpostTHIRDpost。原始问题(虽然不是很清楚)似乎要求在聚合中包含的每个项目前面添加“pre”,例如preFIRSTpostpreSECONDpostpreTHIRDpost - James Daily

4

你可以使用 concat 函数来帮助你。

select string_agg(distinct concat('pre',user.col, 'post'), '')

3
array_to_string(array_agg(distinct column_name::text), '; ')

能够完成工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接