I have a table (call_history) that has multiple records against a single ID in another table (call_detail). I am trying to return a result that will give me a single row for each ID but the most recent entry.
So for example, group all rows against a single ID, but return ONLY the most recent row for the updated_at field (which is a date field).
So far my query...
SELECT MAX(cd.id) as id, cd.first_name, cd.summary, cd.due_at, ch.body, ch.updated_at
FROM call_detail as cd
LEFT JOIN call_history as ch on cd.id = ch.ticket_id
WHERE cd.status = 'open' AND (NOW() > due_at)
GROUP BY cd.id HAVING COUNT(*) > 1
ORDER BY cd.due_at DESC
...returns 'kind' of what I want, but it gives me the oldest entry against the updated_at field. I need it the other way around.
Update
My table structure is as follows:
Call_Detail
id | summary | description | due_at | first_name | last_name
1 | Call 1 | some text | 20/02/2014 17:00:00 | Joe | Bloggs
2 | Call 2 | some text | 18/02/2014 15:00:00 | Fred | Durst
3 | Call 3 | some text | 02/03/2014 01:00:00 | Joe | Bloggs
Call_History
id | ticket_id | body | updated_at | first_name | last_name
1 | 1 | update 1 | 17/02/2014 16:00:00 | Joe | Bloggs
2 | 1 | update 2 | 17/02/2014 16:02:00 | Fred | Durst
3 | 2 | update 1 | 16/02/2014 12:02:00 | Tom | Thumb
4 | 1 | update 3 | 17/02/2014 16:10:00 | Joe | Bloggs
5 | 2 | update 2 | 17/02/2014 01:02:00 | Jack | Reacher
etc...
I need to retrieve the following output:
ticket_id | summary | due_at | first_name | body | updated_at
1 | Call 1 | 20/02/2014 17:00:00 | Joe | Update 3 | 17/02/2014 16:10:00
2 | Call 2 | 18/02/2014 15:00:00 | Fred | Update 2 | 17/02/2014 01:02:00