-1

我有一个包含三个字段 ip_address、contary_name、region_name 的表。

         ip_address         countary_name      region_name
         100.12.34.19           xyz               jk                 
         100.12.34.23           xyz               jk
         170.63.34.41           abc               mn
         170.63.34.42           abc               mn
         170.63.34.43           abc               mn

所以我需要一些这样的查询:

select distinct substring('rex_exp') as common_ip,
       substring('rex_exp') as ip_part,countary_name,region_name
  from table;

输出是

         common_ip      ip_part        countary_name      region_name
         100.12.34.     19,23           xyz               jk                 
         170.63.34.     41,42,43        abc               mn        
4

1 回答 1

2

假设 ip_address 是文本(或 varchar)类型,那么应该这样做:

select common_ip,
       string_agg(ip_part, ',')
       country_name,
       region_name
from (
  select substring(ip_address from '[0-9]{2,3}\.[0-9]{2,3}\.[0-9]{2,3}') as common_ip,
         substring(ip_address from '[0-9]{2,3}$') as ip_part,
         country_name, 
         region_name
  from some_table
) t
group by common_ip, country_name, region_name;

对于旧的 Postgres 版本,您可以将 string_agg 替换为 array_agg 和 array_to_string 的组合

select common_ip,
       array_to_string(array_agg(ip_part), ',')
       country_name,
       region_name
from (
  select substring(ip_address from '[0-9]{2,3}\.[0-9]{2,3}\.[0-9]{2,3}') as common_ip,
         substring(ip_address from '[0-9]{2,3}$') as ip_part,
         country_name, 
         region_name
  from some_table
) t
group by common_ip, country_name, region_name;
于 2012-06-21T06:25:50.387 回答