加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:53:02 所属栏目:百科 来源:网络整理
导读: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=#

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读