postgresql中列的不同值

时间:2018-03-30 10:04:02

标签: sql postgresql split postgresql-9.2

我的下表包含以下数据

amount

我需要一个PostgreSQL脚本,它给我以下输出

id    description
 1    a,b,a

这是我到目前为止所尝试过的。

id   description
1    a,b

1 个答案:

答案 0 :(得分:2)

解决问题的最佳方法是规范化数据模型,不要在单个列中存储多个逗号分隔值。

但是你可以使用unfst和aggregation的组合来实现你想要的东西:

select id, string_agg(distinct c, ',' order by c)
from the_table, unnest(string_to_array(description, ',')) as t(c)
group by id;

对于过时(且不受支持)的9.2版,您需要使用派生表:

select id, string_agg(distinct c, ',' order by c) as description
from (
  select id, unnest(string_to_array(description, ',')) as c
  from the_table
) t
group by id;

在线示例(适用于9.6):http://rextester.com/LEE56363