2009-08-20 59 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

相关问题