一、有关时间的计算
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!=''
以上为个人在使用时遇到的一些例子,后续在使用的过程中继续补充。