Reputation: 148
Edit for clarification:
This is my table:
ID Datetime Date Temp
6043 2016-05-24 10:20:00 2016-05-24 19.3
6042 2016-05-24 10:15:00 2016-05-24 19.1
6041 2016-05-24 10:10:00 2016-05-24 19.1
6040 2016-05-24 10:05:00 2016-05-24 19.1
What I'm trying to do is to select the row with the highest "Temp".
This is my query:
SELECT max(temp) as maxtemp FROM weatherdata WHERE day(date) = 24
The query only gives me the maxtemp, how can I get the ID and Datetime?
Goal is to get the max-value for each day in my table (WHERE day(date) = xx)
Kind Regards
Upvotes: 0
Views: 1787
Reputation: 108641
It looks to me like you are trying to get your entire weatherdata
observation row for the observation that contains the highest temperature in any given month.
This takes two steps, as you have realized. The first step: find the highest temperature observation in each month. You do that like so:
SELECT MAX(temp) temp, LAST_DAY(`datetime`) month_ending
FROM weatherdata
GROUP BY LAST_DAY(`datetime`)
The trick here is to use LAST_DAY()
to figure out in which month each observation occurs. It takes any date, datetime, or timestamp item and figures out the date of the last day of its month. This query gives you a result set containing one temp per month, for the highest temp in the month. Try it. Make sure it works for you.
Next, you should join that to your detailed observation table, like so:
SELECT w.*
FROM weatherdata w
JOIN (
SELECT MAX(temp) temp, LAST_DAY(`datetime`) month_ending
FROM weatherdata
GROUP BY LAST_DAY(`datetime`)
) m ON w.temp = m.temp
AND LAST_DAY(w.`datetime`) = m.month_ending
ORDER BY w.`datetime`
This will give you the detailed observations. Notice that if the highest temperature occurred on more than one observation in any given month, you'll get them all.
Finally, if you only want some months, put this WHERE clause right before the ORDER BY clause
WHERE `datetime` >= '2016-04-01
AND `datetime` < '2016-05-01 -- to get April 2016
Pro tip: don't use names of datatypes, like datetime
, as column names. It makes it hard to troubeshoot your database.
Upvotes: 0