我有一张这样的表
create table events
(
sensor_id integer not null,
event_type integer not null,
value integer not null,
time timestamp unique not null
);
我想要的是显示唯一条目并获取有最长时间的条目,我已经写了这个查询
SELECT B.*
FROM events AS B
RIGHT JOIN (SELECT DISTINCT sensor_id, event_type, MAX(time) AS MaxDateTime
FROM events
GROUP BY sensor_id, event_type
ORDER BY MAxDateTime DESC) A ON B.time = A.MaxDateTime
我想要的是跳过时间列,只显示最终结果中的sensor_id,event_type和值,是否有任何想法?
答案 0 :(得分:1)
如果你希望每sensor_id
行有一行最长时间,那么就像这样:
select e.*
from events e
where e.time = (select max(e2.time)
from events e2
where e2.sensor_id = e.sensor_id
);
编辑:
如果您想要每个传感器和事件的最大值,请将其包含在关联子句中:
select e.*
from events e
where e.time = (select max(e2.time)
from events e2
where e2.sensor_id = e.sensor_id and
e2.event_type = e.event_type
);
答案 1 :(得分:1)
SELECT B.sensor_ID, B.event_Type, B.Value
FROM events AS B
RIGHT JOIN (SELECT distinct sensor_id, event_type, max(time) AS MaxDateTime
FROM events
GROUP BY sensor_id, event_type) A
on B.time = A.MaxDateTime
and B.Sensor_ID = A.Sensor_ID
and B.Event_Type = A.Event_Type
ORDER BY B.Time