简体   繁体   English

如何获取PostgreSQL文本中的最后一个元素?

[英]How to get last element in postgresql Text?

I have a text of elements seperated by , as follows: 我有一个由分隔的元素文本,如下所示:

'{4,56,7,3,2}'

the amount of elemets is unkonwn . 元件的数量未知

How do I get the last element? 如何获得最后一个元素? in the above example 2 在上面的示例2

Try this: 尝试这个:

SELECT regexp_replace('4,56,7,3,2', '^.*,', '')

FIDDLE DEMO 现场演示

EDIT: 编辑:

Try 尝试

SELECT replace(replace(regexp_replace('4,56,7,3,2', '^.*,', ''),'{',''),'}','')

DEMO DEMO

You could use simple text manipulation functions LEFT , strpos and REVERSE : 您可以使用简单的文本操作函数LEFTstrposREVERSE

SELECT val,
     CASE WHEN strpos(REVERSE(val),',') = 0 THEN val
          ELSE REVERSE(LEFT(REVERSE(val), strpos(REVERSE(val),',')-1))  
     END AS last_element
FROM tab;

SqlFiddleDemo

Output: 输出:

╔════════════════╦══════════════╗
║      val       ║ last_element ║
╠════════════════╬══════════════╣
║ 4,56,7,3,2     ║ 2            ║      
║ 1,11111,23121  ║ 23121        ║      
║ 123            ║ 123          ║
║ (null)         ║ (null)       ║
╚════════════════╩══════════════╝

EDIT: 编辑:

WITH cte AS
(
    SELECT REPLACE(REPLACE(val, '{', ''), '}', '') AS val
    FROM tab
)
SELECT val,
     CASE WHEN strpos(REVERSE(val),',') = 0 THEN val
           ELSE REVERSE(LEFT(REVERSE(val), strpos(REVERSE(val),',')-1))  
     END AS last_element
FROM cte;

SqlFiddleDemo2

If the value is indeed stored with the curly braces you can simply cast it into an array and pick the last array element: 如果该值确实与花括号一起存储,则可以将其简单地转换为数组并选择最后一个数组元素:

select (elements::text[])[array_length(elements::text[],1)]
from the_table;

As you didn't include the table definition, I assumed the column is named elements . 由于您未包含表定义,因此我假设该列名为elements

If the column does not contain the curly braces, but just a comma separated list of values, you can still use this approach: 如果列包含大括号,但只是值的逗号分隔的列表,你仍然可以使用这种方法:

select (string_to_array(elements,','))[array_length(string_to_array(elements,','), 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM