我有一个名为“ArchiveTable”的表格:
+---------+-----------------+---------+-----------------+--------------+------------------+ | maxtemp | maxtemptime | mintemp | mintemptime | minwindchill | minwindchilltime | +---------+-----------------+---------+-----------------+--------------+------------------+ | 27.9 | 3/17/2015 16:55 | 25.8 | 3/17/2015 19:00 | 25.8 | 3/17/2015 19:00 | +---------+-----------------+---------+-----------------+--------------+------------------+ | 25.7 | 3/17/2015 19:05 | 19.3 | 3/18/2015 9:05 | 19.3 | 3/18/2015 9:05 | +---------+-----------------+---------+-----------------+--------------+------------------+ | 23.1 | 3/18/2015 19:05 | 18.7 | 3/19/2015 6:30 | 18.7 | 3/19/2015 6:30 | +---------+-----------------+---------+-----------------+--------------+------------------+
我必须选择“maxtemp”的最大值及其对应的“maxtemptime”日期、“mintemp”的最小值及其对应的日期以及“minwindchill”的最小值及其对应的日期。
我知道如何使用 MAX()
和 MIN()
函数获取最大值和最小值,但我无法将这些值与相应的日期关联起来。
最佳答案
如果您可以在不同的行上获取值,那么您可以执行如下操作:
(select a.* from archivetable order by maxtemp limit 1) union
(select a.* from archivetable order by maxtemp desc limit 1) union
. . .
否则,如果你可以这样做:
select atmint.mintemp, atmint.mintempdate,
atmaxt.maxtemp, atmaxt.maxtempdate,
atminwc.minwindchill, atminwc.minwindchilldate
from (select min(mintemp) as mintemp, max(maxtemp) as maxtemp, min(minwindchill) as minwindchill
from archivetable
) a join
archivetable atmint
on atmint.mintemp = a.mintemp join
archivetable atmaxt
on atmaxt.maxtemp = a.maxtemp join
archivetable atminwc
on atminwc.minwindchill = a.minwindchill
limit 1;
限制 1
是因为多行可能具有相同的值。如果是这样,您可以根据您的问题的措辞任意选择其中之一。
关于mysql - 从 MySQL 选择行并使用 MAX 和 MIN 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30700057/