postgresql 相关函数总结

 

 

1.获取当前日期的年份

 

select to_char(t.detect_date,'YYYY')

 

select extract(year from now())为double precision 格式类型

select to_char((SELECT now()::timestamp),'yyyy')

2.获取下一年
select to_char((SELECT now()::timestamp+ '1 year'),'yyyy')
3.获取上一年
select to_char((SELECT now()::timestamp+ '-1 year'),'yyyy')

4.获取指定的时间日期

substring('2019-01-01' from 1 for 7)  输出值为   2019-01

5.获取两个时间点每个月的第一天的日期

select date(zz) from
generate_series(date_trunc('month',to_date('20150305','yyyymmdd')),
date_trunc('month',to_date('20150705','yyyymmdd')),'1 month') as tt(zz);

结果为:

g

 

 

 

 

 

 

 

 

 

 

 

6.日期相加减

 
SELECT now()::timestamp + '1 year';  --当前时间加1年
SELECT now()::timestamp + '1 month';  --当前时间加一个月
SELECT now()::timestamp + '1 day';  --当前时间加一天
SELECT now()::timestamp + '1 hour';  --当前时间加一个小时
SELECT now()::timestamp + '1 min';  --当前时间加一分钟
SELECT now()::timestamp + '1 sec';  --加一秒钟
select now()::timestamp + '1 year 1 month 1 day 1 hour 1 min 1 sec';  --加1年1月1天1时1分1秒
SELECT now()::timestamp + (col || ' day')::interval FROM table --把col字段转换成天 然后相加

 

 

 

 

 

 

7.按日期查询的方法

Timestamp without timezone

方法一:

select * from user_info where create_date >= '2015-07-01' and create_date < '2015-08-15';

方法二:为啥字符串可以按日期格式比较大小

select * from user_info where create_date

between '2015-07-01' and '2015-08-15';

方法三:

select * from user_info where create_date >= '2015-07-01'::timestamp and create_date < '2015-08-15'::timestamp;

方法四:

select * from user_info where create_date between to_date('2015-07-01','YYYY-MM-DD') and to_date('2015-08-15','YYYY-MM-DD');

 

 

 

 

 

 

 

 

 

 

8.显示序号   

 select (ROW_NUMBER () OVER (ORDER BY bb.SUM DESC)) AS xuhao from tb_person

9.获取日期 将01-01前的0 去掉

map.get("score_date").toString().substring(8).replaceFirst("^0*", "") ;

10.获取系统当前月的每天的日期

SELECT
generate_series ( date_trunc( 'month', to_date( to_char( NOW(), 'YYYY-MM-DD' ), 'YYYY-MM-DD' )) :: DATE, NOW() :: DATE, '1 day' ) :: DATE AS datetime

结果如下:

 

 

 

 

 

 

 

 

 

 

 

11.保留7天的日期

delete from  表名  where date_created <(now()-interval '7 day')

posted @ 2019-06-04 08:58  星空物语之韵  阅读(540)  评论(0编辑  收藏  举报