开发者

get last three month records from table

How to get last 3 months records from the table.

SELECT * 
from table 
where month > CURRENT_DATE-120 
  and month < CURRENT_DATE 
order b开发者_如何转开发y month;

I have used the above query is it correct? shall I use this for get last 3 month record from the table.


You can use built-in INTERVAL instruction

Check how this works:

SELECT CURRENT_DATE - INTERVAL '3 months'

and you can rewrite your SQL to:

SELECT * from table where date >  CURRENT_DATE - INTERVAL '3 months'

(not checked but this should give you an idea how to use INTERVAL instruction)


Try that:

SELECT *
FROM table
WHERE month BETWEEN EXTRACT(MONTH FROM NOW() - INTERVAL '3 months')
AND EXTRACT(MONTH FROM NOW())
ORDER BY month
;


This filters the last 3 calendar months

SELECT * from table where date >=  to_char(CURRENT_DATE - INTERVAL '3 months', 'YYYY-MM-01')::date


select date::date
from generate_series((current_date - INTERVAL '1 Month')::date, (current_date - INTERVAL '1 DAY')::date,'1
day'::interval) date
WHERE date >= date_trunc('month', current_date - interval '3' month)
and date < date_trunc('month', current_date)

This will give last three months date list, excluding current months date. Example if current month is November. This list will give use all dates of August, Septemeber and October.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜