Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 by month;

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

like image 243
ungalnanban Avatar asked Jun 25 '10 11:06

ungalnanban


People also ask

How do I get last 3 months data in Hive?

select (date_add(FROM_UNIXTIME(UNIX_TIMESTAMP(), 'yyyy-MM-dd'), 2 - month(FROM_UNIXTIME(UNIX_TIMESTAMP(), 'yyyy-MM-dd')) )); This results in 2015-05-30. The results should be like: if Today is '2015-06-03', then the result of last two months should be like: '2015-04-01'.

How do I get last 6 months records in SQL?

Instead of approximating the "current" date by selecting the MAX(date) the code could reference CAST(GETDATE() as DATE) to access the system datetime and cast it as type DATE. where [date] > dateadd(month, -6, cast(getdate() as date));

How do I get last 30 days from a table in SQL?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).


1 Answers

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)

like image 71
dzida Avatar answered Sep 23 '22 11:09

dzida