postgresql从两行创建一行
我有两行,像这样:postgresql从两行创建一行,postgresql,Postgresql,我有两行,像这样: device ip port vlan network --------------------------------------------- device a ip_address a port_a vlan network device b ip_address b port_b vlan network device_a;device_b;network;ip_address_a;ip_address_b;po
device ip port vlan network
---------------------------------------------
device a ip_address a port_a vlan network
device b ip_address b port_b vlan network
device_a;device_b;network;ip_address_a;ip_address_b;port_a;port_b;vlan
如您所见,两个设备可以共享vlan和网络(点对点网络),而一些设备只能有一个网络和vlan,而不与任何其他设备共享(访问网络)
我想以这样的方式进入决赛:
device ip port vlan network
---------------------------------------------
device a ip_address a port_a vlan network
device b ip_address b port_b vlan network
device_a;device_b;network;ip_address_a;ip_address_b;port_a;port_b;vlan
我是博士后的新手,我被困在这一点上。这应该可以:
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
编辑:由于有一匹没有名字的马,所以简化了。这应该可以:
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
编辑:由于一匹没有名字的马而简化了