Java教程

PG SQL截取字符串到指定字符位置

本文主要是介绍PG SQL截取字符串到指定字符位置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

今天在做PG数据到HIVE的数据交换任务时,因为某个字段在PG中是Varchar类型,hive是bigint,而偏偏PG 中该字段的存储值都被加了小数点位,导致字段类型转换失败。
在这里插入图片描述
现在就需要将字符串中小数点后的部分给截掉。
开始时尝试使用的是CHARINDEX来获取小数点的位置,然后使用substring函数截取该位置之前的数值。

select CAST(SUBSTRING(sal_qty, 1 ,  CHARINDEX('.',sal_qty)-1)as bigint)

但是运行时发现PG中没有CHARINDEX函数。

SQL 错误 [42883]: ERROR: function charindex(unknown, character varying) does not exist
  建议:No function matches the given name and argument types. You might need to add explicit type casts.

在官方文档中查找相应的替换函数
https://www.postgresql.org/docs/current/functions-string.html
找到一个position函数在这里插入图片描述

position ( substring text IN string text ) → integer

Returns first starting index of the specified substring within string, or zero if it's not present.

position('om' in 'Thomas') → 3

测试一下

select sal_qty, cast(SUBSTRING(sal_qty, 1 , position ('.'  in sal_qty) - 1) as bigint) as sal_qty_int from table_test

返回结果,符合预期。
在这里插入图片描述

另外还可以尝试使用strpos函数,功能和position相同,但要注意参数位置
在这里插入图片描述

strpos ( string text, substring text ) → integer

Returns first starting index of the specified substring within string, or zero if it's not present. (Same as position(substring in string), but note the reversed argument order.)

strpos('high', 'ig') → 2
select sal_qty, cast(SUBSTRING(sal_qty, 1 ,  strpos(sal_qty,'.')-1)as bigint) as sal_qty_int from table_test
这篇关于PG SQL截取字符串到指定字符位置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!