我有一张这样的表
测量
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
的测量结果?
它可以是测量模型或只是SQL查询的示例,感谢任何帮助!
答案 0 :(得分: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)
答案 1 :(得分:0)
我相信这会奏效:SELECT * FROM table WHERE object_id = (SELECT MAX(object_id) FROM table)
答案 2 :(得分: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))