Mysql - How to select previous month’s records?

Asked

Viewed 22 times

-1

Hello, I’m trying to select the 'Customers' table records that were registered last month. In this table there is the field 'Createdate' (datetime). I’m trying to do it this way but it’s not just returning the records from last month, but from the months of past years as well. Example: if last month is March my query is returning March of all the years that are on the table.

I’m doing like this:

SELECT Id, Name, CreateDate FROM Clientes WHERE MONTH(CreateDate) = MONTH(DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)); 
  • I think I got it this way:

  • SELECT Id, Name, Createdate FROM Clients WHERE MONTH(Createdate) = MONTH(DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)) AND YEAR(Createdate) = YEAR(NOW());

  • The problem is that this way that I found when the month of January will not return anything and I need to return December of the previous year. Someone knows how to fix this?

1 answer

0

Hello! Try it like this:

SELECT Id, Name, Createdate FROM Clients WHERE Createdate >= DATE_ADD(SYSDATE(), INTERVAL -1 MONTH)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.