Return the last entry of different Postgresql objects

1

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?

    
asked by anonymous 12.02.2015 / 11:58

3 answers

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:

  • join selects the car and all its events through the expression E.CARRO_ID = C.ID
  • Subselect only the most recent date of all events for that car
  • In this way, the second join clause causes the query to only return the event whose date is the largest
  • 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.

        
    12.02.2015 / 12:55
    0

    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.

        
    12.02.2015 / 12:01
    0

    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
    

    link

        
    13.02.2015 / 18:47