views:

44

answers:

3

Currently I am performing a left join on two tables. The first table has an id and a persons name, the second table has an id, the id of a person from table 1, and then a timestamp (of the last flight they had).

People                             Flights
id   |  name             id   |   person_id   | time
------------             ---------------------------
1       Dave              1         1          1284762115
2       Becky             2         1          1284787352
                          3         2          1284772629
                          4         2          1286432934
                          5         1          1289239480

When I perform my left join, I get a list of people and their flight times, but what I would like is just the list of people with their last flight times.

So SELECT p.id, p.name, f.time FROM People p LEFT JOIN Flights f ON p.id = f.person_id

Returns

1 Dave  1284762115
1 Dave  1284787352
1 Dave  1289239480
2 Becky 1284772629
2 Becky 1286432934

I would like to see just:

1 Dave  1289239480
2 Becky 1286432934

So I need to return only the match with the highest f.id or the highest f.time

+4  A: 
SELECT
    p.id, p.name, MAX(f.time) AS LastFlight
FROM
    People p
    LEFT JOIN Flights f ON p.id = f.person_id
GROUP BY
    p.id, p.name
CyberDude
This is awesome, thanks. Simple and elegant.
Nick Brown
A: 
SELECT p.id, p.name, f.time FROM People p LEFT JOIN 
  (select person_id, max(time) time from flights group by person_id) f 
ON p.id = f.person_id
Jim Garrison
`max(time)` needs a column alias I think?
Martin Smith
Yes, i left it out by accident; fixed.
Jim Garrison
+1  A: 

Try this:

;with LastFlightTimes as 
(
select person_id, max(id) maxid
from Flights f
group by person_id
)
SELECT p.id, p.name, f.time FROM People p 
LEFT JOIN LastFlightTimes lft ON p.id = lft.person_id
left join Flights f on f.id = lft.maxid
Denis Valeev