MySQL:选择按日期分组的最大值对应行
我有一张每小时温度表:MySQL:选择按日期分组的最大值对应行,mysql,sql,database,group-by,max,Mysql,Sql,Database,Group By,Max,我有一张每小时温度表: id timestamp temperature 我想为每天选择最高温度和相应的时间戳 select max(temperature), timestamp from table group by date(from_unixtime(timestamp)) 不起作用,因为它总是返回第一行的时间戳(但我需要最高温度行的时间戳) 任何建议都将不胜感激。试试这个 select max(temperature), timestamp from temp group
id timestamp temperature
我想为每天选择最高温度和相应的时间戳
select max(temperature), timestamp from table group by date(from_unixtime(timestamp))
不起作用,因为它总是返回第一行的时间戳(但我需要最高温度行的时间戳)
任何建议都将不胜感激。试试这个
select max(temperature), timestamp from temp group by UNIX_TIMESTAMP(date(timestamp));
使用这样的子查询
select * from temp WHERE temperature=(select min(temperature) from temp)
选择每个日期的最高温度,然后将其放回温度和日期表的联接中,这将允许您选择与温度和日期匹配的行。在大多数情况下,联接将比子查询快,而且无论如何,您不能总是在子查询中分组 使用
date()
SELECT temperature, timestamp
FROM temp t
JOIN (
SELECT date(from_unixtime(timestamp)) as dt,
max(temperature) as maxTemp
FROM temp
GROUP BY date(from_unixtime(timestamp))
) m ON (
t.temperature = m.maxTemp AND
date(from_unixtime(t.timestamp)) = m.dt
)
但是,我建议将表更改为将时间戳存储为timestamp
,而不是varchar
或int
,并在插入数据时执行一次转换,而不必在整个查询中进行转换。从长远来看,这将使事情更容易阅读和维护。如果将时间戳更改为实际的时间戳
,则会出现相同的查询:
SELECT temperature, timestamp
FROM temp t
JOIN (
SELECT date(timestamp) as dt,
max(temperature) as maxTemp
FROM temp
GROUP BY date(timestamp)
) m ON (
t.temperature = m.maxTemp AND
date(t.timestamp) = m.dt
)
只是更容易阅读,而且可能更快,这取决于您拥有的数据量。您还可以使用隐式联接编写,这可能更易于阅读。这取决于你的品味
SELECT temperature, timestamp
FROM temp t, (
SELECT date(timestamp) as dt,
max(temperature) as maxTemp
FROM temp
GROUP BY date(timestamp)
) m
WHERE t.temperature = m.maxTemp
AND date(t.timestamp) = m.dt
我敢肯定,现在我说得太多了。