使用MAX和GROUP BY选择所有相应的字段

时间:2009-08-20 09:38:41

标签: sql mysql group-by max greatest-n-per-group

我有这张桌子:

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

2 个答案:

答案 0 :(得分:15)

没有一个主键字段,我认为最好的选择是:

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 :(得分: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