2009-08-20 62 views
11

我有這個表:選擇使用MAX和組的所有相應的字段BY

alt text

,我想提出,將返回每個deal_id最高timestamp和該行的請求相應的status_id

所以在這個例子中,我將返回2行:

1226, 3, 2009-08-18 12:10:25 
1227, 2, 2009-08-17 14:31:25 

我試圖與此查詢

SELECT deal_id, status_id, max(timestamp) FROM deal_status GROUP BY deal_id 

做到這一點,但它會返回錯誤status_id

1226, 1, 2009-08-18 12:10:25 
1227, 1, 2009-08-17 14:31:25 
+0

的可能重複[獲取具有最大值列的行](http://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column) – outis 2011-12-23 02:32:14

回答

14

沒有一個主鍵字段,我認爲你最好的選擇是:

select * from deal_status 
inner join 
    (select deal_id as did, max(timestamp) as ts 
    from deal_status group by deal_id) as ds 
    on deal_status.deal_id = ds.did and deal_status.timestamp = ds.ts 

這個,如果你允許具有同時

+1

您的答案几乎是完美的,你只需要把'as ds'放在括號外。 – tachfine 2009-08-21 04:25:17

0

嗨,我希望這同一產品兩種不同的狀態仍然無法工作給予什麼ü希望它

select deal_id,status_id, timestamp from deal_status 
inner join 
    (select deal_id as did,max(timestamp) as ts 
    from deal_status group by deal_id )as ds 
    on deal_status.deal_id = ds.did and deal_status.timestamp = ds.ts order by deal_id 
+0

您所寫的代碼與接受的答案中的代碼基本相同 – 2013-05-14 09:24:10

相關問題