I have a table something like this:
----------------------------------------
|uID|responseDate|field_01|field_02|etc|
+---+------------+--------+--------+---+
| 1 | 2011-12-02 | yes | no | |
| 2 | 2011-11-25 | no | yes | |
| 1 | 2012-01-02 | no | yes | |
| 2 | 2012-12-01 | no | no | |
| 3 | 2010-01-02 | yes | no | |
+---+------------+--------+--------+---+
I would like to get uIDs and responseDates for whom the latest response to field_01 is ‘yes’ – so my query should return:
------------------
|uID|responseDate|
+---+------------+
| 3 | 2010-01-02 |
+---+------------+
I’m using an inner join, but incorrectly. Here is my query:
SELECT f.uID, f.responseDate
FROM form_05 as f
INNER JOIN (
SELECT uID, max(responseDate) AS latest_date
FROM form_05
WHERE field_01 = 'yes'
GROUP BY uID ) dmax
ON dmax.uID = f.uID and dmax.latest_date = f.responseDate
ORDER BY f.uID ASC;
What this returns, however, is the latest entries for each uID where field_01 is yes, i.e.:
------------------
|uID|responseDate|
+---+------------+
| 1 | 2011-12-02 |
| 3 | 2010-01-02 |
+---+------------+
But I don’t want that. I’d like to make it so that only the latest entry for each uID is eligible for the test. How can I restructure the query? Any pointers are greatly appreciated.
Give this a try and let me know if it doesn’t work: