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','yyyymmdd')),'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,date_trunc('year', 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=#
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。