I would like to select several colums. In one column there are two distinct values "top" and "bot". Every row has a timestamp. I would like to make sure, that for each value "top" and "bot" I do get the latest timestamp entry.
Table:
uid | datetime | device | temp | hum
================================================
1 |2022-08-30 17:34:34 |top |11.5 |88.90
2 |2022-08-30 17:34:22 |bot |13.2 |88.90
3 |2020-10-06 13:48:33 |top |24.3 |75.00
4 |2020-10-06 14:35:37 |bot |21.7 |75.00
I would like to get the following result with the SQL statement:
datetime | device | temp | hum
===========================================
2022-08-30 17:34:34 |top |11.5 |88.90
2022-08-30 17:34:22 |bot |13.2 |88.90
But what I get with my current statement is:
datetime | device | temp | hum
===========================================
2020-10-06 13:48:33 |top |24.3 |75.00
2020-10-06 14:35:37 |bot |21.7 |75.00
So it's not the most current row, it is the oldest one.
My best SQL try so far is:
SELECT datetime, device, temp, hum
FROM <table_name>
WHERE uid=123456789
GROUP BY device
ORDER BY datetime DESC
LIMIT 2
CodePudding user response:
This one should work fine for you:
SELECT device, datetime
FROM table_name
WHERE datetime in (SELECT MAX(datetime) FROM table_name GROUP BY device)