postgresql中列的不同值

Posted

技术标签:

【中文标题】postgresql中列的不同值【英文标题】:distinct values for column in postgresql 【发布时间】:2018-03-30 10:04:01 【问题描述】:

我有下表和以下数据

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;

【问题讨论】:

请澄清。您至少可以提供CRATE TABLEINSERT 语句作为示例吗? XML 是从哪里来的? 【参考方案1】:

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

但是您可以使用非嵌套和聚合的组合来实现您想要的:

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

【讨论】:

你错过了嵌套 我遇到错误错误:FROM 中的函数表达式不能引用相同查询级别的其他关系第 11 行:来自测试,unnest(string_to_array(description,',')) as t(c ) 在执行此查询时创建临时表测试(id 整数,描述文本);插入测试选择 1,'a,b,a'; select id, string_agg(distinct c, ',' order by c) from test, unnest(string_to_array(description,',')) as t(c) group by id; @KAN:我忘了你过时的 Postgres 版本不支持。查看我的编辑。

以上是关于postgresql中列的不同值的主要内容,如果未能解决你的问题,请参考以下文章

如何根据pig中列的不同值拆分关系

更新查询以根据不同表中的值更改一个表中列的现有值

如何遍历大型 Pyspark Dataframe 中列的不同值? .distinct().collect() 引发大任务警告

比较两个数据框中列的值

比较两个数据帧中列的值

如何将sqlalchemy中列的默认值设置为关系中列的值?