我有下表和下面的数据
id description
1 a,b,a
我需要一个能给出以下输出的 PostgreSQL 脚本
id description
1 a,b
这是我到目前为止所尝试的。
create temporary table test
(
id integer,
description text
);
insert into test
select 1,'a,b,a';
select id,string_agg(distinct description, ',') as description
from test
group by id;
最佳答案
您的问题的最佳解决方案是规范化您的数据模型,并且不要在单个列中存储多个逗号分隔值。
但是您可以结合使用 unnest 和聚合来实现您想要的:
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
关于sql - postgresql 中列的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572383/