来自 MySQL 的 Select 行和分组使用 MAX 和 MIN

Select rows from MySQL and grouping use MAX and MIN

我有以下 table 称为 '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   |
+---------+-----------------+---------+-----------------+--------------+------------------+

我必须select'maxtemp'的最大值及其对应的'maxtemptime'日期,'mintemp'的最小值及其对应的日期,以及[的最小值=25=]及其对应的日期。

我知道如何使用 MAX()MIN() 函数获取最大值和最小值,但我无法将这些值与相应的日期相关联。

看到这个MySQL Handling of GROUP BY

如果我理解正确的话你应该这样做

SELECT field1, field2, fieldN, COUNT(field1) AS alias FROM table
  GROUP BY field1
 HAVING maxtemp  = MAX(maxtemp); -- I think this is not correct

虽然我不是 100% 确定该解决方案,但您也可以试试这个

SELECT field1, field2, fieldN, COUNT(field1) AS alias FROM table
  GROUP BY field1
 HAVING maxtemp  = (SELECT MAX(maxtemp) FROM table);

如果您可以在不同的行上取值,那么您可以这样做:

(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;

limit 1 是因为多行可能具有相同的值。如果是这样,您可以根据您的问题措辞任意选择其中之一。