我有下表名为'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()
函数获取最大值和最小值,但我无法将这些值与相应的日期相关联。
答案 0 :(得分:0)
请参阅此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);
答案 1 :(得分:0)
如果您可以在不同的行上获取值,那么您可以执行以下操作:
(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
是因为多行可能具有相同的值。如果是这样,你可以根据问题的表达方式任意选择其中一个。