我的表具有以下结构:
sensor_id | timestamp | value
-----------|------------|-------
1 | 1516905900 | 100.1
4 | 1516916920 | 90.4
... | ... | ...
我需要为给定的sensor_id 选择每天具有最大值的列。我需要与结果中每个最大值关联的时间戳。
我使用 MAX()、GROUP BY 和 DATE_FORMAT 取得了一些成功,但我无法让我的查询包含与每个组的最大值关联的时间戳。
这是我到目前为止所拥有的:
select DATE_FORMAT(from_unixtime(timestamp), '%m/%d/%Y') as x, max(value) from sensor_log where sensor_id=6 group by x;
结果仅包含 x 和 max(value) 列。我认为可能可以使用某种 JOIN 来获取其余的列,但我还没有弄清楚。
我可以预见的另一个问题是,sensor_id 可能会在同一天多次出现最大值,在这种情况下,我只想保留当天第一次出现的该值。
最佳答案
嗯。这听起来像是对相关子查询的一个很好的利用:
select date(from_unixtime(sl.timestamp)) as dte, sl.sensor_id, sl.value, sl.timestamp
from sensor_log sl
where sl.timestamp = (select sl2.timestamp
from sensor_log sl2
where sl2.sensor_id = sl.sensor_id and
date(from_unixtime(sl2.timestamp)) = date(from_unixtime(sl.timestamp))
order by sl2.value desc, sl.timestamp asc
limit 1
);
关于mysql - 选择包含每天最大值的整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261252/