1
Supposing 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?
1
Supposing 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?
1
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 should 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.
0
distinct on
return only one row for each carro_id
. In the clause order by
decide which one.
select distinct on (carro_id) *
from
carro
inner join
evento using(carro_id)
order by carro_id, data desc, hora desc
http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
0
If you’re just looking for 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)
The DISTINCT
is used to avoid repetitions.
This will list all events, not only the last in relation to the car.
Browser other questions tagged sql postgresql
You are not signed in. Login or sign up in order to post.
This solution has been useful to me, thank you utluiz!!
– cvhg