postgres常用语句和错误处理办法

一、有关时间的计算

1、当前时间

select now();            2020-03-17 14:51:08.409262+08
select current_timestamp;    2020-03-17 14:51:08.409262+08

2、当前日期

select current_date;       2020-03-17

3、当前时间

select current_time;        14:59:53.047984+08

4、两种计算年龄的方法

按当前日期计算
select  (current_date- date('2010-01-01'))/365   
指定日期
select  (to_date('2019/01/01','yyyy-DD-mm')- date(left(csrq,10)))/365

5、从时间里取年/月/日

select extract(year from now());     2020
select extract(month from now());   3
select extract(day from now());    17

6、字符串转日期

SELECT  to_date('2016/01/01','yyyy-DD-mm');    2016-01-01

7、根据当前时间计算年龄并分组
csrq的格式: 1982-10-14T00:00:00+08:00

SELECT xm,csrq,age,
(case when  age<30 then 'A' 
	when age>=30 and age<40 then 'B' 
	when age>=40 and age<50 then 'C' 
	when age>=50 and age<60 then 'D' 
	when age>=60 and age<70 then 'E' 
	when age>=70 and age<80 then 'F' 
	when age>=80 then 'G' 
END) AS GP FROM (SELECT xm,csrq,(current_date- date(left(csrq,10)))/365 as age
from table) as dd

xm csrq age gb
张三 1982-10-14T00:00:00+08:00 37 B

二、有关数据的计算

1、取n位有效数字

SELECT round(2.22552,2)     2.23

2、计算个数

select count(*);

3、求和

select sum(A_colum)

4、求平均数

select  AVG(A_colum)

5、字符串转数字

SELECT cast('12345.2' as FLOAT8)      12345.2
SELECT cast('12345' as int)           12345
SELECT cast('12345.2' as int)         会报错
SELECT cast('12345.2' as numeric)     整数和浮点数都可以

三、异常处理
1、 字符串转数字时报错:

select cast(zz as numeric) from table

ERROR: invalid input syntax for type numeric: “”
原因:zz列中有空值

正确方法:

select cast(zz as numeric) from table  where zz!=''

以上为个人在使用时遇到的一些例子,后续在使用的过程中继续补充。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值