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.
In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.
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.
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!
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));
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With