【问题标题】:How to aggregate all the resulted rows column data in one column?如何将所有结果行列数据聚合在一列中?
【发布时间】:2020-11-27 12:58:33
【问题描述】:

我有一个案例驱动的查询。下面是最简单的形式

select Column 1 from mytable 

结果:

    Column 1        
   latinnametest
   LatinManual
   LatinAuto

是否可以在另一列中显示所有结果行的第 1 列数据的聚合数据,例如每行前面的第 5 列,用逗号分隔?

预期:

Column 1         Column 2
latinnametest  latinnametest,LatinManual,LatinAuto
LatinManual    latinnametest,LatinManual,LatinAuto
LatinAuto      latinnametest,LatinManual,LatinAuto

我使用了 array_aggconcat() 但它在第 2 列中聚合了相同的行数据,但未按预期添加所有行列数据以逗号分隔。请帮忙。

编辑: 我已经尝试了下面提到的解决方案,但我在列中得到了重复的数据。看截图。我将鼠标悬停在最后一列上并查看重复数据。有什么解决办法吗? [![在此处输入图片描述][1]][1]

【问题讨论】:

  • @a_horse_with_no_name 感谢您通知我。在标签中添加它是我的错误!

标签: postgresql string-aggregation


【解决方案1】:

你可以使用string_agg()作为窗口函数:

select column_1, 
       string_agg(column_1, ',') over () as all_values
from the_table;

编辑,范围改变后:

如果您需要不同的值,请使用派生表:

select column_1, 
       string_agg(column_1, ',') over () as all_values
from (
  select distinct column_1
  from the_table
) t;

或者使用公用表表达式:

with vals as (
  select string_agg(distinct column_1, ',') as all_values
  from the_table 
)
select t.column_1, v.all_values
from the_table t
  cross join vals v

【讨论】:

  • 我确实使用了这个,但是,在那一栏中我得到了大量的数据,相同的数据被重复了。有什么方法可以使用 distinct 吗?它说ERROR: DISTINCT is not implemented for window functions LINE 11: string_agg( distinct (case when
  • 谢谢我已经集成,它按预期工作。 .非常感谢
猜你喜欢
  • 2023-01-26
  • 1970-01-01
  • 2023-02-24
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多