2012-03-26 24 views
9

Ho una tabella mysql con tre colonne: nome utente, posizione, data/ora. Si tratta fondamentalmente di un registro delle attività dell'utente in quale posizione si trovano e nel momento in cui si trovavano lì.Query SQL per la selezione distinta con la data/ora più recente prima

Quello che voglio fare è selezionare un nome utente distinto + posizione dove viene fornito solo l'elemento più recente (per data/ora).

Così dicono che il tavolo è costituito da:

tom roomone 2011-3-25 10:45:00 
tom roomtwo 2011-3-25 09:00:00 
tom roomtwo 2011-3-25 08:30:00 
pam roomone 3011-3-25 07:20:23 

vorrei solo questi per essere selezionati:

tom roomone 2011-3-25 10:45:00 
tom roomtwo 2011-3-25 09:00:00 

risposta

15

provare la seguente query con table1 come tablename:

select username, location, max(timestamp) from table1 
group by username, location 
1

Questa risposta in realtà non garantisce che le altre colonne abbiano lo stesso record del nome utente/data/ora, ma il seguente wil l (usando una sottoquery).

select t1.* 
from (
    select ForeignKeyId,AttributeName, max(Created) AS MaxCreated 
    from YourTable 
    group by ForeignKeyId,AttributeName 
) t2 
join YourTable t1 
on t2.ForeignKeyId = t1.ForeignKeyId 
and t2.AttributeName = t1.AttributeName 
and t2.MaxCreated = t1.Created 

Risposta disponibili all'indirizzo:

Select distinct most recent

Problemi correlati