在多列中选择不同的值,并用列标签保存在公共列中。

问题描述 投票:0回答:1

我在postgres中有一个有两列的表。

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

我可以在各个列中找到 distinct,但不能在一个列中添加标签源。

下面是我使用的查询。

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

任何建议将是非常有帮助的。

postgresql distinct
1个回答
2
投票

你可以取消pivot的列,并将它们汇总回来。

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;

在线示例

另外,如果你不想列出每一列,你可以将行转换为JSON值,然后取消pivot。

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;
© www.soinside.com 2019 - 2024. All rights reserved.