I have a MySQL database with lots of entrys with columns like "local_time", "temp", "wind", etc.
What I want to archive is get in just one query the MIN value for temp, the MAX value for temp in each day with the datetime for min and max.
eg:
local_time | temp
2022-12-01 12:20 | 10
2022-12-01 12:40 |20
2022-12-02 19:00 | 12
2022-12-02 20:05 | 8
2022-12-03 22:22 | 14
2022-12-03 22:30 | 16
Result I wanted for query:
date | min | min_date | max | max_date| avg
2022-12-01 | 10 | datetime | 20 | datetime | avg_value
2022-12-02 | 8 | datetime | 12 | datetime | avg_value
2022-12-03 | 14 | datetime | 16 | datetime | avg_value
For now, I’m using this query:
select DATE(local_time) as local_time, MIN(temp) as max, MAX(temp) as min, AVG(temp) as avg FROM data GROUP BY DATE(local_time);
But I need the datetime (local_time) for the MIN value and MAX value, for every single day.
Any help is welcome.
For now, I’m using this query:
select DATE(local_time) as local_time, MIN(temp) as max, MAX(temp) as min, AVG(temp) as avg FROM data GROUP BY DATE(local_time);
But I need the datetime (local_time) for the MIN value and MAX value, for every single day.
3
Answers
I din’t get it working in one go so I joined two queries:
a group by query to get your min, max and average and
one using window functions to get mindate for min and maxdate for max:
https://www.db-fiddle.com/f/owZiLJuKhqc4DF6XYa3aJV/0
I guess the query with window functions leaves space for optimizing…
EDIT
Just wondered if a version only with window functions would perform better(It’s nicer to look at anyway):
https://www.db-fiddle.com/f/owZiLJuKhqc4DF6XYa3aJV/2
If you multiple identical Min values or MAX values for that matter, you need to adjust the subqueries
Schema (MySQL v8.0)
Query #1
View on DB Fiddle
You say you want the time for the minimum temperature and the time for the maximum temperature per day, but rather than using singular you should use the plural. Yes, there is one minimum and maximum temperature per day, but there is not necessarily one time when that minimum resp. that maximum temperature is reached. These temperatures can occur multiple times a day. We must first determine a rule what to do in case of such ties, then find the algorithm.
Let’s say we are looking for the first time the minimum was reached and the last time the maximum was reached. (We could look at well vice versa or collect all times one of the temperatures is met.)
We need two steps: First, find the minimum and maximum temperatures per day, then aggregate the data to get one row per day.
Well, if you were looking for the first time the maximum temperature is reached, that would be
of course, and if you were looking for all the times that temperature occured in the day, it would be something along the lines of