1

In my database I have profile ids with statuses which also have a timestamp. I want to have the latest status for each profile using a query. How can I do this the easiest way?

So f.e. for:

Id      Profile  Timestamp
-------------------------
1        1       1550588089
2        1       1550588099
3        3       1550588183
4        4       1550588333
5        4       1550588534
6        4       1550588377

I want to have

Id      Timestamp
-------------------------
2       1550588099
3       1550588183
5       1550588534
Rick James
  • 135,179
  • 13
  • 127
  • 222
Klyner
  • 3,983
  • 4
  • 26
  • 50

3 Answers3

1

You can use correlated subquery

DEMO

select id as status, Timestamp
from tablename a where timestamp in (select max(timestamp) from tablename b where a.profile=b.profile )

OUTPUT:

tatus   Timestamps
2       1550588099
3       1550588183
5       1550588534

OR you can use row_number()

select * from 
(
select *, row_number() over(partition by profile order by timestamp desc) as rn
from tablename
)A where rn=1
Fahmi
  • 37,315
  • 5
  • 22
  • 31
1

use row_number() which support maximum dbms

 select * from 
(
 select *,row_number() over(partition by Id order by timestamp desc) rn
 from table
) t where t.rn=1
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
0

This query:

select profile, max(timestamp) maxtimestamp 
from tablename
group by profile 

returns all the maximum timestamps for each profile.
So you get what you need by joining it to the main table:

select id, timestamp
from tablename t
inner join (
  select profile, max(timestamp) maxtimestamp 
  from tablename
  group by profile 
) g
on g.profile = t.profile and g.maxtimestamp = t.timestamp

See the demo

forpas
  • 160,666
  • 10
  • 38
  • 76