sql - postgresql 中列的不同值

标签 sql postgresql split postgresql-9.2

我有下表和下面的数据

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/

相关文章:

php - 使用 PHP 和 MySQL 实现购物车的策略

java - 在 Eureka Streams 之上构建大规模可扩展且安全的社交网络?

python - 如何根据字符数和分隔符将字符串拆分为 block ?

c++ - 如何将数据文件分成几个部分

mysql - 在不同的行上选择满足不同条件的值?

mysql - 某个日期范围内的 COUNT CASE 函数

sql - 使用 HiveQL 分解结构数组

sql - 复杂的 SQL 查询有助于聚合嵌套子查询的值

sql - 如何生成当前日期前 6 个月的平均支出

php - 如何用 php 打破数组中的印地语字符串并计算字符串中有多少字母和元音