Assuming I have two tables: Car containing: plate, year, ect .. Event containing: car, lat, long, date, time, etc. How could I return only the last entry of each car in the event table?
Assuming I have two tables: Car containing: plate, year, ect .. Event containing: car, lat, long, date, time, etc. How could I return only the last entry of each car in the event table?
It would be something like:
SELECT C.*, E.*
FROM CARRO C
JOIN EVENTO E
JOIN E.CARRO_ID = C.ID
AND E.DATA_HORA = (
SELECT MAX(DATA_DATA)
FROM EVENTO E2
WHERE E2.CARRO_ID = E.CARRO_ID
)
The explanation:
E.CARRO_ID = C.ID
Note that the field must have the date and time and should not have two events at the same time, otherwise you can select two events. There is a way around this, but it would be almost a gambiarra, it is more reasonable not to have two events at the same time.
If you are just wanting to query the data, you can use the following query ...
SELECT DISTINCT evt.carro, evt.lat, evt.long, evt.data, evt.hora, etc...
FROM Evento evt, Carro car
WHERE evt.carro = car.placa AND (evt.carro, evt.data) IN
(SELECT carro, data
FROM Evento, Carro
WHERE data >= ALL AND Evento.carro = Carro.placa)
DISTINCT
is used to avoid repetition.
distinct on
will return only one row for each carro_id
. In the order by
clause it is decided which one.
select distinct on (carro_id) *
from
carro
inner join
evento using(carro_id)
order by carro_id, data desc, hora desc