2014-02-17 92 views
0

我有一個表(call_history),它具有針對另一個表(call_detail)中的單個ID的多個記錄。我正在嘗試返回一個結果,該結果會爲每個ID提供一個行,但最近的條目會顯示一行。如何返回GROUP BY語句的最新記錄

因此,例如,針對單個ID對所有行進行分組,但只返回updated_at字段(它是日期字段)的最新行。

到目前爲止,我查詢...

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 

...返回「種」我想要的東西,但它給我對抗的updated_at領域最早的條目。我需要另一種方式。

更新

我的表結構如下:

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 

等等

我需要檢索的輸出如下:

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 
+0

這聽起來像你可能想與某些值的MAX有關的細節(可能是Call_Detail ID列,可能是Call_History中的某個列),但對錶的描述還不清楚。請在每個表格中包含顯着列的骨架模式,甚至可能包含一些示例數據和該數據的預期輸出。我想你會在通話記錄表上需要一些更復雜的計算,但我還不確定。 –

+0

提供表格的框架 –

+1

此問題已在StackOverflow上提出並回答了數百次。請參閱[tag:most-n-per-group]標籤。 –

回答

1

嘗試此查詢。你需要從call_history最近的記錄,因此你首先應該與這些日期的子查詢(見CH_MAX子查詢),然後用ticket_idupdated_at JOIN:

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

+0

完美!感謝您花時間爲我解決這個問題 - 非常感謝!仍然試圖讓我的頭,但它確實是我需要的。再次感謝! – Riples