0

I have a SQL table where I am trying to extract the latest data for each category.

My table schema

| deviceId                    | varchar(30) | NO   |     | NULL    |       |
| rssi                        | varchar(15) | YES  |     | NULL    |       |
| space_temperature           | varchar(30) | YES  |     | NULL    |       |
| control                     | varchar(30) | YES  |     | NULL    |       |
| counter                     | varchar(30) | YES  |     | NULL    |       |
| timestamp                   | varchar(30) | NO   |     | NULL    |       |
| date                        | varchar(30) | NO   |     | NULL    |       |
| floor                       | varchar(30) | YES  |     | NULL    |       |
| Id                          | varchar(5)  | YES  |     | NULL    |       |

I want to fetch the latest row for each Id.

select * from Data where floor = 'L2' and date = '2019-12-10' group by Id; 

This is giving me a row for each Id, but it is giving me the first entry but not the latest entry in the table.

I tried with

select *,max(timestamp) as latest_timestamp from Data where floor = 'L2' and date = '2019-12-10' group by Id; 

This is giving the latest timestamp but the other columns have the data of the first entry. How to get the results of the latest entry for each Id group?

Dale K
  • 25,246
  • 15
  • 42
  • 71
chink
  • 1,505
  • 3
  • 28
  • 70

1 Answers1

1

You can try below way -

select * from Data a where floor = 'L2' and date = '2019-12-10'
and timestamp =(select max(timestamp) from data b where a.id=b.id)
Fahmi
  • 37,315
  • 5
  • 22
  • 31