1

我有一张这样的桌子

测量

id    object_id   generated_at (v)    
110   4           2012-11-13 10:29:00   
109   4           2012-11-13 10:28:00   
108   4           2012-11-13 10:27:00
107   3           2012-11-13 10:26:00
106   3           2012-11-13 10:25:00
105   4           2012-11-13 10:24:00
104   4           2012-11-13 10:23:00
103   1           2012-11-13 10:22:00
102   1           2012-11-13 10:21:00
...

generated_at列排序。

我的问题:有没有选择的能力

id    object_id   generated_at (v)    
110   4           2012-11-13 10:29:00   
109   4           2012-11-13 10:28:00   
108   4           2012-11-13 10:27:00

最后一组(按 排序generated_at)相同的测量值object_id

它可以是 Rails 中用于测量模型的示例,也可以是 SQL 查询,感谢您的帮助!

4

3 回答 3

2

您最初的问题显然想要最近组中的对象,而不是所有对象。为此,您需要计算最大对象 id 和其他对象的最大生成时间:

select *
from t cross join
     (select max(object_id) maxobject_id from t) maxt
where object_id = maxt.maxobject_id and
      generated_at > (select max(generated_at) from t where object_id <> maxt.maxobject_id)
于 2012-11-13T18:15:13.847 回答
0

以下查询将获得结果:

select * from Measurements
left join Measurements as M2
on
(M2.generated_at > Measurements.generated_at and M2.object_id <> Measurements.object_id)
where 
M2.id IS NULL
and
Measurements.object_id = 
(select object_id from Measurements where generated_at = (select MAX(generated_at) from Measurements))
于 2012-11-13T18:29:04.990 回答
0

我相信这会奏效:SELECT * FROM table WHERE object_id = (SELECT MAX(object_id) FROM table)

于 2012-11-13T17:57:58.247 回答