Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

Tags:

datetime

mysql

I need some help writing a MySQL query to show me rows from last month, but not the whole month, only up and until the same day, hour and minute as it is now(), but 1 month before.

So for example, if today is 5/19 at 5:25pm I need to select rows from midnight 12:00am 4/1 to 5:25pm of 4/19 (from the same year too of course).

Thanks!

like image 700
newyuppie Avatar asked May 19 '11 20:05

newyuppie


People also ask

Which function in MySQL can be used to get the date after 1 month?

Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column.

How do I extract data from a specific month in SQL?

To select all entries from a particular month in MySQL, use the monthname() or month() function. The syntax is as follows. Insert some records in the table using insert command. Display all records from the table using select statement.

What is the data type for now () in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).


2 Answers

You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.

select    * from   yourtable t where   /* Greater or equal to the start of last month */   t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and   /* Smaller or equal than one month ago */   t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH) 
like image 171
GolezTrol Avatar answered Sep 25 '22 14:09

GolezTrol


Getting one month ago is easy with a single MySQL function:

SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH); 

or

SELECT NOW() - INTERVAL 1 MONTH; 

Off the top of my head, I can't think of an elegant way to get the first day of last month in MySQL, but this will certainly work:

SELECT CONCAT(LEFT(NOW() - INTERVAL 1 MONTH,7),'-01'); 

Put them together and you get a query that solves your problem:

SELECT * FROM your_table WHERE t >= CONCAT(LEFT(NOW() - INTERVAL 1 MONTH,7),'-01') AND t <= NOW() - INTERVAL 1 MONTH 
like image 21
Ike Walker Avatar answered Sep 23 '22 14:09

Ike Walker