[英]PostgreSQL - How do I extract a string that is before a comma OR between a delimiter/comma, but only where the value after the comma is greater than 0
[英]PostgreSQL - Extract string before ending delimiter
我有一列看起来像这样的数据:
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有点矫kill过正,但这是为了更好地揭示逻辑。
使用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
参见演示 。
结果:
| result |
| ------ |
| 102 |
| 58 |
| 58 |
| 57 |
| 106 |
可以使用substring()
的正则表达式来完成。 如果你想:
最后一个逗号之前只有数字的最长字符串 :
substring(data, '(\d+)\,[^,]*$')
或者您可能想要:
最后一个逗号(',')之前的字符串,该字符串开头用冒号(':')或字符串开头。
可能是另一个正则表达式:
substring(data, '([^:]*)\,[^,]*$')
或这个:
reverse(split_part(split_part(reverse(data), ',', 2), ':', 1))
比(昂贵的)正则表达式更冗长,但通常要快得多。
db <> 在这里拨弄
以下将源字符串视为“数组数组”。 似乎每个数据元素都可以定义为S(x,y),整个字符串都可以定义为S1:S2:... Sn。 然后,任务变为从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)的情况,则最后一次选择减少以选择Sn [1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.