mysql - 从 MySQL 选择行并使用 MAX 和 MIN 进行分组

标签 mysql sql group-by

我有一个名为“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/

相关文章:

sql - 使用 SQL 查询查找外键关系

mysql - 给定订单,每个组获取一条记录

php - PHP/SQL语法问题

MYSQL 为每个用户选择最快的时间和最低的点击次数

mysql - 在sql中使用for语句从2个表中选择

sql - MySQL IS NOT NULL 和 != '' 之间的区别

r - 汇总多组列

MySQL - 按一列分组并获得最低值

php - 在 MySQL 中使用许多 bool 列是否比结合 PHP 的较长字符串更快?

mysql - 狂欢 : Command line argument issue