使用正则表达式POSIX进行postgres查询

时间:2012-06-21 05:10:17

标签: regex postgresql

我有一个包含三个字段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        

1 个答案:

答案 0 :(得分:2)

假设ip_address是text(或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版本,您可以将array_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;