[英]MySQL: Select multiple columns but with the latest value of one column for each distinct value
I would like to select several colums.我想 select 几列。 In one column there are two distinct values "top" and "bot".
在一列中有两个不同的值“top”和“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.
我想确保,对于每个值“top”和“bot”,我确实获得了最新的时间戳条目。
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:我想通过 SQL 语句得到以下结果:
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:到目前为止,我最好的 SQL 尝试是:
SELECT datetime, device, temp, hum
FROM <table_name>
WHERE uid=123456789
GROUP BY device
ORDER BY datetime DESC
LIMIT 2
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.