如何在汇总字段中获取重复记录

时间:2019-05-22 20:21:49

标签: sql postgresql

我已经准备好查询:

Startup.cs

我得到的结果是:

SELECT
building_custom."Location Code",
building_custom."RUD Site Name",
string_agg(concat_ws('-',subnet.range_begin,subnet.range_end),',')
FROM building
INNER JOIN building_custom ON building.building_pk=building_custom.building_fk
INNER JOIN device ON building.building_pk=device.building_fk
INNER JOIN ipaddress ON device.device_pk=ipaddress.device_fk
INNER JOIN subnet ON ipaddress.subnet_fk=subnet.subnet_pk
GROUP BY
building_custom."Location Code",
building_custom."RUD Site Name"

最后一个字段(子网范围)包含重复的值。

目标是取得如下结果:

DBA;BUENOS AIRES-ARENALES;141.167.161.17-141.167.161.18,10.120.10.1-10.120.10.30,10.120.11.1-10.120.11.254,141.167.161.25-141.167.161.30,10.120.16.1-10.120.16.254,10.120.10.1-10.120.10.30,10.120.16.1-10.120.16.254,10.120.11.1-10.120.11.254,0.0.0.1-255.255.255.254,141.167.161.25-141.167.161.30,141.167.161.25-141.167.161.30,10.120.11.1-10.120.11.254,10.120.16.1-10.120.16.254,141.167.161.21-141.167.161.22,0.0.0.1-255.255.255.254,10.120.10.1-10.120.10.30

起初我想添加

DBA;BUENOS AIRES-ARENALES;0.0.0.1-255.255.255.254,10.120.10.1-10.120.10.30,10.120.11.1-10.120.11.254,10.120.16.1-10.120.16.254,141.167.161.17-141.167.161.18,141.167.161.21-141.167.161.22,141.167.161.25-141.167.161.30

但是后来我需要在GROUP BY中添加它,结果甚至更糟:

DISTINCT ON (view_subnet_v1.range_begin)

1 个答案:

答案 0 :(得分:0)

您可以尝试在内部查询中使用distinct:

 SELECT
    "Location Code",
    "RUD Site Name" ,
    string_agg(concat_ws('-',range_begin,range_end),',') from 
    (SELECT distinct 
    building_custom."Location Code",
    building_custom."RUD Site Name",
    subnet.range_begin
    ,subnet.range_end
    FROM building
    INNER JOIN building_custom ON building.building_pk=building_custom.building_fk
    INNER JOIN device ON building.building_pk=device.building_fk
    INNER JOIN ipaddress ON device.device_pk=ipaddress.device_fk
    INNER JOIN subnet ON ipaddress.subnet_fk=subnet.subnet_pk
) inner_q
    GROUP BY
    "Location Code",
    "RUD Site Name"

此外,如果您只想拥有最宽的子网,则可以在内部查询中使用minmaxgroup by而不是distinct