select 多列中的不同值并保存在带有列标签的公共列中

select distinct values in multiple column and save in common column with column tags

我在 postgres 中有一个包含两列的 table:

col1    col2
a       a
b       c
d       e
f       f

我想在两列上区分并制作一列,然后从它来的地方分配列名标签。期望的输出是:

col   source
a     col1, col2
b     col1
c     col1
d     col1
e     col1
f     col1, col2

我能够在各个列中找到不同的,但无法创建单个列并添加标签源。

下面是我正在使用的查询:

select distinct on (col1, col2) col1, col2 from table

任何建议都会很有帮助。

您可以取消对列的透视并将它们聚合回来:

select u.value, string_agg(distinct u.source, ',' order by u.source)
from data
  cross join lateral (  
     values('col1', col1), ('col2', col2)
  )as u(source,value)
group by u.value
order by u.value;

Online example

或者,如果您不想列出每一列,您可以将行转换为 JSON 值,然后取消旋转:

select x.value, string_agg(distinct x.source, ',' order by x.source)
from data d
  cross join lateral jsonb_each_text(to_jsonb(d)) as x(source, value)
group by x.value  
order by x.value;