PostgreSQL 类型转换

–1 例子
postgres=# select 1/4;
?column?

    0

(1 row)

    在PG里如果想做除法并想保留小数,用上面的方法却行不通,因为"/" 运算结果为取整,并

且会截掉小数部分。

–2 类型转换
postgres=# select round(1::numeric/4::numeric,2);
round

0.25
(1 row)

备注:类型转换后,就能保留小数部分了。

–3 也可以通过 cast 函数进行转换
postgres=# select round( cast ( 1 as numeric )/ cast( 4 as numeric),2);
round

0.25
(1 row)

–4 关于 cast 函数的用法
postgres=# SELECT substr(CAST (1234 AS text), 3,1);
substr

3
(1 row)

–5 附: PostgreSQL 类型转换函数

函数 返回类型 描述 实例
to_char(timestamp,text) text 把时间间隔转换为字符串 to_char(current_timestamp,“HH12:MI:SS”)
to_char(interval,text) text 把时间间隔转换为字串 to_char(interval’15h 12m 12s’,‘HH24:MI:SS’)
to_char(int,text) text 把整型转换为字串 to_char(125,‘999’)
to_char(double,precision) text 把实数/双精度数转换为字串 to_char(125.8::real,‘999D9’)
to_char(numeric,text) text 把numeric转换为字串 to_char(-125.8,‘999D99S’)
to_date(text,text) date 把字串转换为日期 to_date(‘05 Dec 2000’,‘DD Mon YYYY’)
to_timetamp(text,text) timestamp 把字串转换为时间戳 to_timestamp(‘05 Dec 2000’,‘DD Mon YYYY’
to_timetamp(double) timestamp 把unix纪元转换为时间戳 to_timestamp(200120400)
to_number(text,text) numeric 把字串转换为numeric to_number(‘12 454.8-’,‘99G999D9S’

参考:
https://www.jianshu.com/p/2d72e2a455d0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值