我有这样的 2 行:
device ip port vlan network
---------------------------------------------
device a ip_address a port_a vlan network
device b ip_address b port_b vlan network
如你所见,2台设备可以共享vlan和网络(点对点网络),有些设备只能有一个网络和vlan,不与任何其他设备共享(接入网络)
我想像这样进入决赛:
device_a;device_b;network;ip_address_a;ip_address_b;port_a;port_b;vlan
我是 Postgres 的新手,我被困在这一点上。
最佳答案
应该这样做:
select string_agg(distinct device,';') ||
';' || string_agg(distinct network,';') ||
';' || string_agg(distinct ip,';') ||
';' || string_agg(distinct port,';') ||
';' || string_agg(distinct vlan,';')
from your_table
这里有一个小例子来说明这个方法:
with dt as (
select 'device_a'::text col1, 'network'::text col2
union all
select 'device_b'::text col1, 'network'::text col2
)
select string_agg(distinct col1,';') ||
';' || string_agg(distinct col2,';')
from dt
编辑:由于 a_horse_with_no_name 而简化。
关于postgresql 从两行创建一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592234/