简体   繁体   English

postgresql中列的不同值

[英]distinct values for column in postgresql

I have the following table with below data 我有下表和以下数据

id    description
 1    a,b,a

I need a PostgreSQL script that give me below output 我需要一个PostgreSQL脚本,它可以为我提供以下输出

id   description
1    a,b

This what I have tried so far. 到目前为止,我已经尝试过了。

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;

The best solution for your problem is to normalize your data model and don't store multiple, comma separated values in a single column. 解决问题的最佳解决方案是规范化数据模型,并且不要在单个列中存储多个逗号分隔的值。

But you can achieve what you want using a combination of unnest and aggregation: 但是您可以结合使用嵌套和聚合来实现所需的功能:

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

With the outdated (and unsupported) version 9.2 you need to use a derived table: 对于过时(且不受支持)的版本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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM