PostgreSQL 给定日期间隔初始时间计算

PostgreSQL 给定日期间隔初始时间计算,第1张

概述1.功能说明: date_trunc: 截取给定时间(TIMESTAMP,date),获得指定精度(时,天,月,年)的初始使时间 2.一般时间 date_trunc('hour',TIMESTAMP '2018-08-16 20:38:40') Result: 2018-08-16 20:00:00 date_trunc('day',TIMESTAMP '2018-08-16 20:38:40')

1.功能说明:

date_trunc: 截取给定时间(TIMESTAMP,date),获得指定精度(时,天,月,年)的初始使时间


2.一般时间

date_trunc('hour',TIMESTAMP '2018-08-16 20:38:40')

Result:2018-08-16 20:00:00

date_trunc('day',TIMESTAMP '2018-08-16 20:38:40')

Result:2018-08-16 00:00:00

date_trunc('month',TIMESTAMP '2018-08-16 20:38:40')

Result:2018-08-01 00:00:00

date_trunc('year',TIMESTAMP '2018-08-16 20:38:40')

Result:2018-01-01 00:00:00


3.特殊需求:

给定时间段的每年的所有月份的第一天,最后一天,下月第一天

-- Result: month_first_day,month_end_day,next_month

select date(zz) as month_first_day,date(zz + interval '1 month' - interval '1 day') as month_end_day,date(zz + interval '1 month') as next_month

from generate_serIEs(date_trunc('year',to_date('20180510','yyyymmdd')),date_trunc('year',to_date('201905','1 month') as tt(zz);


sql结果:

month_first_day | month_end_day | next_month

-----------------+---------------+------------

2018-01-01 | 2018-01-31 | 2018-02-01

2018-02-01 | 2018-02-28 | 2018-03-01

2018-03-01 | 2018-03-31 | 2018-04-01

2018-04-01 | 2018-04-30 | 2018-05-01

2018-05-01 | 2018-05-31 | 2018-06-01

2018-06-01 | 2018-06-30 | 2018-07-01

2018-07-01 | 2018-07-31 | 2018-08-01

2018-08-01 | 2018-08-31 | 2018-09-01

2018-09-01 | 2018-09-30 | 2018-10-01

2018-10-01 | 2018-10-31 | 2018-11-01

2018-11-01 | 2018-11-30 | 2018-12-01

2018-12-01 | 2018-12-31 | 2019-01-01

2019-01-01 | 2019-01-31 | 2019-02-01

(13 rows)



找出指定时间小时,天,月,年的初始值


-- Result: dtrunc_hour,dtrunc_day,dtrunc_month,dtrunc_year

SELECT date_trunc('hour',TIMESTAMP '2018-08-16 20:38:40') as dtrunc_hour,date_trunc('day',TIMESTAMP '2018-08-16 20:38:40') as dtrunc_day,date_trunc('month',TIMESTAMP '2018-08-16 20:38:40') as dtrunc_month,TIMESTAMP '2018-08-16 20:38:40') as dtrunc_year;


sql结果:


dtrunc_hour | dtrunc_day | dtrunc_month | dtrunc_year

---------------------+---------------------+---------------------+---------------------

2018-08-16 20:00:00 | 2018-08-16 00:00:00 | 2018-08-01 00:00:00 | 2018-01-01 00:00:00

(1 row)


postgres=#

总结

以上是内存溢出为你收集整理的PostgreSQL 给定日期间隔初始时间计算全部内容,希望文章能够帮你解决PostgreSQL 给定日期间隔初始时间计算所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1172829.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-02
下一篇 2022-06-02

发表评论

登录后才能评论

评论列表(0条)

保存