Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning records from the last 3 months only in MySQL

Tags:

mysql

I have a table with a timestamp field. How do I get data from the last 3 months?

In particular, March is my current month let say, 03/2012. I need to return records from the months March, February, and January only.

like image 777
user1783933 Avatar asked Mar 13 '13 21:03

user1783933


People also ask

How do I get last 3 months records in SQL?

In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.

How do I get previous month records in MySQL?

Similarly, if you want to get records for past one month rolling, that is, last 30 days, then here's the SQL query for it. select * from orders where order_date>now() - interval 1 month; In the above query, we select rows after past 1 month interval.

How do I get last 12 months in MySQL?

mysql> select * from users where date_joined> now() - INTERVAL 12 month; In the above query, we use system function now() to get current datetime. Then we use INTERVAL clause to filter those records where order_date falls after an interval of 12 months before present datetime. That's it!

How do I get last 6 months data in SQL Server?

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));


1 Answers

3 months before today:

select * from table where timestamp >= now()-interval 3 month; 

Start with first of month:

select * from table where timestamp >= last_day(now()) + interval 1 day - interval 3 month; 
like image 71
AlwaysBTryin Avatar answered Sep 21 '22 11:09

AlwaysBTryin