Select rows from MySQL and grouping use MAX and MIN

77 Views Asked by At

I have the following table called '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   |
+---------+-----------------+---------+-----------------+--------------+------------------+

I have to select the maximum value of 'maxtemp' and its corresponding 'maxtemptime' date, minimum value of 'mintemp' and its corresponding date, and minimum value of 'minwindchill' and its corresponding date.

I know how to obtain the max and min values with the MAX() and MIN() functions, but I cannot associate these values to the corresponding date.

2

There are 2 best solutions below

2
On BEST ANSWER

If you could take the values on separate rows, then you could do something like this:

(select a.* from archivetable order by maxtemp limit 1) union
(select a.* from archivetable order by maxtemp desc limit 1) union
. . .

Otherwise, if you can do something like this:

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;

The limit 1 is because multiple rows might have the same values. If so, you can arbitrarily choose one of them, based on how your question is phrased.

0
On

See this MySQL Handling of GROUP BY

If I understood you correctly you should do something like this

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

Although I'm not 100% sure about that solution you could try this as well

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