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

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=#

Ubuntu 16.04 下安装 PostgreSQL 和 phpPgAdmin 

Linux下RPM包方式安装PostgreSQL 

Linux下安装PostgreSQL 

Linux下PostgreSQL安装部署指南 

Linux下安装 PostgreSQL 并设置基本参数 

Fedota 24 将数据库升级到 PostgreSQL 9.5 

CentOS 6.5下PostgreSQL服务部署 

MongoDB 的详细介绍请点这里
MongoDB 的下载地址请点这里

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c74574126efee8711e5be989a5973528.html