PostgreSQL截取字符串到指定字符位置详细示例
今天在做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') → 2select sal_qty, cast(SUBSTRING(sal_qty, 1 , strpos(sal_qty,'.')-1)as bigint) as sal_qty_int from table_test
总结
到此这篇关于PostgreSQL截取字符串到指定字符位置的文章就介绍到这了,更多相关PGSQL截取字符串到指定位置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
PostgreSQL的整型、浮点型、固定精度数值和序列等数字类型
PostgreSQL(简称PGSQL)是一种开源关系型数据库管理系统,广泛应用于企业级应用,文章详细介绍了PostgreSQL的数字类型,包括整型、浮点型、固定精度数值型和序列类型,强调了选择合适的数字类型对于数据库的存储效率、查询性能和数据准确性的重要性2024-09-09
postgresql rank() over, dense_rank(), row_number()用法区别
这篇文章主要介绍了postgresql rank() over, dense_rank(), row_number()的用法区别,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-12-12
PostgreSQL使用MySQL作为外部表(mysql_fdw)
PostgreSQL 提供了一种访问和操作外部数据源的机制,称为外部数据包装器,本文主要给大家介绍了PostgreSQL使用MySQL作为外部表的方法,感兴趣的朋友跟随小编一起看看吧2022-11-11


最新评论