View Full Version : SQL for last month
Daryl
01-05-2011, 07:18 AM
I am using the following query to find records for last month
SELECT * FROM application JOIN company JOIN users WHERE YEAR(application.application_date) = YEAR(CURDATE()) AND MONTH(application.application_date) = MONTH(CURDATE())-1 AND application.consultant_company = company.co_id AND application.consultant= users.id ORDER BY application.application_date DESC
However this does not work this month for last month. Any idea why and what I should change the sql too to get it to work?
Ray Borduin
01-05-2011, 07:45 AM
That is because you are using:
MONTH(CURDATE())-1
and this being month 1, then that would look for a return value of month 0, when you actually want month 12.
Instead try:
MONTH(CURDATE() - INTERVAL 1 MONTH)
Daryl
01-05-2011, 07:57 AM
Thanks Ray
But this doesn't show results from December 2010 either.
Ray Borduin
01-05-2011, 07:58 AM
That is because you would also have to use:
YEAR(application.application_date) = YEAR(CURDATE() - INTERVAL 1 MONTH)
Daryl
01-05-2011, 08:24 AM
Thanks Ray!!
Would
YEAR(CURDATE() - INTERVAL 2 MONTH)
show data from 2 months ago?
Ray Borduin
01-05-2011, 08:30 AM
yes it would.
Daryl
01-05-2011, 08:34 AM
Excellent!
Thanks again!
Daryl
03-30-2011, 04:40 AM
What is the best code for PHP to do the same?
I am using;
For this month
<?php $date = date('F'); echo "$date";?>
For 1 month ago
<?php
$mnth = date('F');
$prev_mnth = date('F',strtotime("-1 months")); // "previous month" works also
echo $prev_mnth;
?>
But they are both showing March today
For 2 months ago
<?php
$mnth = date('F');
$prev_mnth = date('F',strtotime("-2 months")); // "previous month" works also
echo $prev_mnth;
?>
But this shows January as expected...
Daryl
03-30-2011, 05:14 AM
This solution shows March instead of February too...
<?php
$last_month_time = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$last_month = date('F', $last_month_time);
echo "$last_month";
?>
Daryl
03-30-2011, 05:18 AM
This one works!
<?php echo date('F', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
?>
vBulletin® v3.8.1, Copyright ©2000-2012, Jelsoft Enterprises Ltd.