当前位置:Gxlcms > 数据库问题 > PostgreSQL时间段查询

PostgreSQL时间段查询

时间:2021-07-01 10:21:17 帮助过:348人阅读

1.今日

select *  from "表名" 
where to_date("时间字段"::text,‘yyyy-mm-dd‘)=current_date

2.昨日

select *  from "表名" 
where to_date("时间字段"::text,‘yyyy-mm-dd‘)=current_date - 1

3.最近半个月

select *  from "表名" 
where to_date("时间字段"::text,‘yyyy-mm-dd‘) BETWEEN current_date - interval ‘15 day‘  AND current_date

4.最近6个月

select *  from "表名" 
where to_date("时间字段"::text,‘yyyy-mm-dd‘) BETWEEN current_date - (‘6month ‘ || extract(day from CURRENT_DATE) -1 || ‘ day‘)::interval  AND current_date

说明:

extract(day from CURRENT_DATE) 提取当前时间的天数,因为查询最近六个月,比如现在2018年11月14日,查询的时间区间是
2018年5月1日 - 2018年11月14日 

当前时间减去6个月和13天,得到2018年5月1日(如果减去14天得到的是2018年4月30日)
select current_date - (‘6 month ‘ || extract(day from CURRENT_DATE) -1 || ‘ day‘)::interval as beginMonth ;

 查询结果:2018-05-01 00:00:00

 

PostgreSQL时间段查询

标签:extract   当前时间   highlight   res   inter   pre   to_date   说明   text   

人气教程排行