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

在将PG数据库中的数据迁移至Hive时遇到字段类型不匹配的问题,由于PG中的varchar字段含有小数点,而Hive需要bigint类型。文章介绍了如何利用PostgreSQL的position或strpos函数来截取并转换带有小数点的字符串,成功解决了数据转换中的类型冲突问题。通过测试,解决方案已证实有效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在做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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值