简体   繁体   English

PostgreSQL在逗号分隔的值列表中获取最后一个值

[英]PostgreSQL get last value in a comma separated list of values

In a PostgreSQL table I have a column which has values like 在PostgreSQL表中,我有一列,其值类似于

AX,B,C
A,BD
X,Y
J,K,L,M,N

In short , it will have a few comma separated strings in the column for each record. 简而言之,每条记录的列中都会有一些逗号分隔的字符串。 I wanted to get the last one in each record. 我想获得每个记录中的最后一个。 I ended up with this. 我结束了这个。

select id, reverse(substr(reverse(mycolumn),1,position(',' in reverse(mycolumn)))) from mytable order by id ; 

Is there an easier way? 有更容易的方法吗?

With regexp_replace : 使用regexp_replace

select id, regexp_replace(mycolumn, '.*,', '')
from mytable
order by id;

我会这样:

select reverse(split_part(reverse(myColumn), ',', 1))

Is there an easier way? 有更容易的方法吗?

With your current data, Gordon's answer works best imo. 使用当前数据,Gordon的答案最适合imo。 Other options would be a regex (messy), or converting the column to a text[] array eg ('{' || col || '}')::text[] or variations thereof. 其他选项将是正则表达式(混乱),或将列转换为text []数组,例如('{' || col || '}')::text[]或其变体。

If you were using a text[] array instead of plain text for your column, you'd want to use array functions directly: 如果您在列中使用text []数组而不是纯文本,则需要直接使用数组函数:

select col[array_length(col, 1)]

http://www.postgresql.org/docs/current/static/functions-array.html http://www.postgresql.org/docs/current/static/functions-array.html

Example with dummy data: 虚拟数据示例:

 with bar as (
 select '{a,b,c}'::text[] as foo
 )
 select foo[array_length(foo, 1)] from bar;

You could, of course, also create a parse_csv() function or get_last_csv_value() function to avoid writing the above. 当然,您也可以创建parse_csv()函数或get_last_csv_value()函数来避免编写上述内容。

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

相关问题 计算用逗号分隔的值,并且不要将逗号放在最后一个值中 - Count values separated by commas and don't put comma in the last value 如何将逗号分隔值放入括号内具有多个逗号分隔值的行中 - How to get comma separated values into rows with having multiple comma separated value inside brackets Postgresql:将两个值添加到以逗号分隔的列? - Postgresql: add two values to a column separated by a comma? 用逗号提取 Substring Postgresql 中的分隔值 - Extract Substring in Comma Separated values in Postgresql 查询以逗号分隔返回列值 - postgresql - Query to return column values as comma separated - postgresql 从逗号分隔列表中的联接表中获取多个列值 - Get multiple column values from joined table in a comma separated list PostgreSQL 查询以逗号分隔列表的形式返回结果 - PostgreSQL query to return results as a comma separated list 从Oracle数据库中的逗号分隔值中获取特定值 - Get specific value from a comma separated values in Oracle database 从 SQL 中的逗号分隔值获取第一个或第二个值 - Get first or second values from a comma separated value in SQL 如何获取不在逗号分隔的字符串的第一个或最后一个索引中但在MySQL的字符串中间索引的值 - How to get values not indexed in the first or in the last in a comma separated string but in the middle of the string in MySQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM