Forum Moderators: coopster
$appt_sql = "SELECT a.ssn,MAX(a.date_next_appt),c.fname,c.lname,c.ssn FROM activity as a INNER JOIN client_info as c ON a.ssn=c.ssn WHERE (MAX(a.date_next_appt) > '$date_from' AND MAX(a.date_next_appt) < '$date_to') GROUP BY c.fname,c.lname,c.ssn";
the reason I need the most recent date being with in the date range is that there may be several entries for a client and there may be a more recent entry for that client so if they have a activity.next_appt_date with in the range but isnt that client's most recent, I dont want that client returned. This may be simple but I am not very familiar with complex MySql queries. Any help would be greatly appreciated.
How about using BETWEEN [dev.mysql.com] and LIMIT [dev.mysql.com]?
$ssn = 1234567890;
$appt_sql = "SELECT
a.ssn,
a.date_next_appt,
c.fname,
c.lname,
c.ssn
FROM activity AS a
INNER JOIN client_info AS c
ON a.ssn = c.ssn
WHERE a.ssn = $ssn
AND a.date_next_appt BETWEEN '$date_from' AND '$date_to'
ORDER BY a.ssn, a.date_next_appt
LIMIT 1
";
client_info table:
fname:John lname:Doe ssn:12345
fname:Joe lname:Jenkins ssn:23451
activity table:
ssn:12345 next_appt_date:2004-10-01
ssn:12345 next_appt_date:2004-10-08
ssn:23451 next_appt_date:2004-10-01
ssn:23451 next_appt_date:2004-10-06
row returned within range i gave above:
fname:Joe lname:Jenkins ssn:23451 next_appt_date:2004-10-06
note:John Doe wasnt returned because his max next_appt_date was '2004-10-08' and didnt fall into the range.
SELECT a.ssn, MAX(a.next_appt_date), c.fname, c.lname FROM activity AS a INNER JOIN client_info AS c ON a.ssn = c.ssn WHERE a.next_appt_date BETWEEN '$date_from' AND '$date_to' GROUP BY a.ssn, c.fname, c.lname ORDER BY c.fname, c.lname, a.ssn;
You must include columns in your GROUP BY that are part of the SELECT column list. Also, I'm not sure you want MAX here, you may actually want MIN.
$appt_sql = "SELECT a.ssn, MAX(a.date_next_appt) as apptdate, c.fname, c.lname FROM activity AS a INNER JOIN client_info AS c ON a.ssn = c.ssn GROUP BY a.ssn, c.fname, c.lname HAVING MAX(a.date_next_appt) BETWEEN '$date_from' AND '$date_to'";