Monday, 6 August 2018

How to query mysql for previous month?

I was working on a php project, where i wanted to count the total number of clients for last previous month, starting from 1st to 30th. For example, if the current month is Sep 2012, i wanted to find the count of clients i received for the August 2012.
You need not bang your head converting time with php. You can directly use this sql statement.
select count(*) as total from table_clients WHERE  `email` LIKE ‘ex@example.com’
and YEAR(date) = YEAR(CURRENT_DATE – INTERVAL 1 MONTH)
AND MONTH(date) = MONTH(CURRENT_DATE – INTERVAL 1 MONTH)

$rset = mysql_query("select count(*) as total from table_invoices WHERE  `email` LIKE 'ex@example.com'
and YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)");

0 comments:

Post a Comment