PostgreSQL截取字符串到指定字符位置詳細示例
今天在做PG數據到HIVE的數據交換任務時,因為某個字段在PG中是Varchar類型,hive是bigint,而偏偏PG 中該字段的存儲值都被加了小數點位,導致字段類型轉換失敗。
現在就需要將字符串中小數點后的部分給截掉。
開始時嘗試使用的是CHARINDEX來獲取小數點的位置,然后使用substring函數截取該位置之前的數值。
select CAST(SUBSTRING(sal_qty, 1 , CHARINDEX('.',sal_qty)-1)as bigint)
但是運行時發(fā)現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
總結
到此這篇關于PostgreSQL截取字符串到指定字符位置的文章就介紹到這了,更多相關PGSQL截取字符串到指定位置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
PostgreSQL 實現定時job執(zhí)行(pgAgent)
這篇文章主要介紹了PostgreSQL 實現定時job執(zhí)行(pgAgent),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01解決postgreSql 將Varchar類型字段修改為Int類型報錯的問題
這篇文章主要介紹了解決postgreSql 將Varchar類型字段修改為Int類型報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12PostGresql 實現四舍五入、小數轉換、百分比的用法說明
這篇文章主要介紹了PostGresql 實現四舍五入、小數轉換、百分比的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01