1. 程式人生 > >PostgreSQL時間段查詢

PostgreSQL時間段查詢

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