欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2024/1/1 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 ) → integerReturns 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 ) → integerReturns 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截取字符串到指定字符位置的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。