Question

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
Was it helpful?

Solution

Try this query. You need the most recent record from call_history so first you should make a subquery with these dates (see CH_MAX subquery) and then JOIN with ticket_id and updated_at:

SELECT cd.id as id, 
       cd.first_name, 
       cd.summary, 
       cd.due_at, 
       ch.body, 
       ch.updated_at 
FROM call_detail as cd 

LEFT JOIN 
 ( SELECT ticket_id, MAX(updated_at) as max_updated_at 
          FROM call_history 
          GROUP BY ticket_id
  ) as CH_MAX ON cd.id = CH_MAX.ticket_id

LEFT JOIN call_history as ch ON cd.id = ch.ticket_id 
                                AND CH_MAX.max_updated_at = ch.updated_at

WHERE cd.status = 'open' AND (due_at<NOW()) 
ORDER BY cd.due_at DESC

SQLFiddle demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top