Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL-在结束分隔符之前提取字符串_Sql_Postgresql - Fatal编程技术网

PostgreSQL-在结束分隔符之前提取字符串

PostgreSQL-在结束分隔符之前提取字符串,sql,postgresql,Sql,Postgresql,我有一列数据,如下所示: 58,0:102,56.00 52,0:58,68 58,110 57,440.00 52,0:58,0:106,6105.95 我需要提取最后一个分隔符(',')之前的字符 使用上述数据,我想得到: 102 58 58 57 106 我不能保证这是最好的方式,但这是一种方式: with splits as ( select string_to_array(bar, ',') as bar_array from foo ), second_to_last a

我有一列数据,如下所示:

58,0:102,56.00
52,0:58,68
58,110
57,440.00
52,0:58,0:106,6105.95
我需要提取最后一个分隔符(',')之前的字符

使用上述数据,我想得到:

102
58
58
57
106

我不能保证这是最好的方式,但这是一种方式:

with splits as (
  select string_to_array(bar, ',') as bar_array
  from foo
),
second_to_last as (
  select
    bar_array[cardinality(bar_array)-1] as field
  from splits
)
select
  field,
  case
    when field like '%:%' then split_part (field, ':', 2)
    else field
  end as last_item
from second_to_last

我在CTE上做得有点过火,但这是为了更好地暴露逻辑。

使用CTE,删除最后一个逗号后的所有内容,然后将其余部分拆分为一个数组:

with cte as (
  select
    regexp_split_to_array(
      replace(left(col, length(col) - position(',' in reverse(col))), ':', ','),
      ','
    ) arr                                             
  from tablename  
)  
select arr[array_upper(arr, 1)] from cte
请参阅。
结果:


可以使用中的正则表达式完成。如果需要:
最后一个逗号前最长的数字字符串

substring(data, '(\d+)\,[^,]*$')
或者您可能想要:
最后一个逗号(“,”)之前的字符串,该逗号在开头由冒号(“:”)或字符串开头分隔。
可能是另一个regexp:

substring(data, '([^:]*)\,[^,]*$')
或者这个:

reverse(split_part(split_part(reverse(data), ',', 2), ':', 1))
更详细,但通常比(昂贵的)正则表达式快得多


dbfiddle

以下内容将源字符串视为“数组数组”。似乎每个数据元素都可以定义为S(x,y),整个字符串可以定义为S1:S2:…Sn。 然后,任务变成从序列号中提取x

with as_array as 
     ( select string_to_array(S[n], ',') Sn 
         from (select string_to_array(col,':') S
                    , length(regexp_replace(col, '[^:]','','g'))+1  n 
                 from tablename 
              ) t
     )
select Sn[array_length(Sn,1)-1] from as_array

上面将S(x,y)扩展到S(a,b,…,x,y),任务仍然是从Sn中提取x。如果所有原始子字符串S都被格式化为S(x,y),则最后一次选择将减少到选择序列号[1]

我需要提取字符。
您所需的结果列出的是数字,而不是字符。请澄清。定义你认为除了所提到的字符之外的字符。
with as_array as 
     ( select string_to_array(S[n], ',') Sn 
         from (select string_to_array(col,':') S
                    , length(regexp_replace(col, '[^:]','','g'))+1  n 
                 from tablename 
              ) t
     )
select Sn[array_length(Sn,1)-1] from as_array