Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with average subquery

Tags:

sql

mysql

I am making a SQL query towards a weather database, i need the wind_direction and windspeed.
This is my currect query:

SELECT wind_direction,
       windspeed
  FROM weather
  WHERE time >= curdate() and
        time < (curdate() + interval 1 day) AND
        windspeed > 0
  ORDER BY wind_direction ASC

This will remove all values where windspeed = 0 and will only show data for today.

Query output:

wind_direction   windspeed  
0               10.1  
0               11.2  
23              7.6  
23              1.4  

As you can see i get duplicate values which is understandable, but my graphing system does not support this, it does not know which value to use.
What i need is one unique wind_direction and the avg() windspeed for that direction.

like image 780
HyperDevil Avatar asked Dec 07 '25 03:12

HyperDevil


1 Answers

SELECT  wind_direction, AVG(windspeed)
FROM    weather
WHERE   time >= curdate() and time < (curdate() + interval 1 day)
        AND windspeed > 0
GROUP BY
        wind_direction
ORDER BY
        wind_direction ASC

If you want a single wind_direction, say, that with the greatest average speed, use this:

SELECT  wind_direction, AVG(windspeed) AS avg_speed
FROM    weather
WHERE   time >= curdate() and time < (curdate() + interval 1 day)
        AND windspeed > 0
GROUP BY
        wind_direction
ORDER BY
        avg_speed DESC 
LIMIT 1
like image 121
Quassnoi Avatar answered Dec 08 '25 17:12

Quassnoi