I want to access a weather table and sumamrise it in terms of days and months. I want some of the values to be AVG and some to be SUM.
I want to underpin the resulting record with values from the collective data that represent the maximum count but after a few combinations, I have not managed it.
EXAMPLE DATA:
day_date main_weather temp
2012-01-01 07:00:00 Cloudy 8.0
2012-01-01 08:00:00 Cloudy 10.0
2012-01-01 09:00:00 Sunny 12.0
2012-01-01 10:00:00 Sunny 16.0
2012-01-01 11:00:00 Sunny 18.0
WANTED RESULT:
DATE(day_date) MAX(COUNT(main_weather) AVG(temp)
2012-01-01 Sunny 12.8
Here's my first SQL to show what I am trying to do:
SELECT
DATE(`day_date`),
MAX(COUNT(`main_weather`)), <--- this is the piece I am stuck with the max values.
AVG(`temp`)
FROM `sma_weather`
GROUP BY `day_date`;
For your second example, the query return only one row because you have added the option LIMIT 1
. FOr the rest, I don't really understand your description of the result that you want to get so I cannot help you. It wouldn't hurt to give a litle example with a few lines of data so that people can understand what you are trying to achieve.
Looks like a correlated subquery would do it, but not sure how well this will scale.
SELECT
DATE(`day_date`) AS day
, (
SELECT w1.`main_weather`
FROM `weather` w1
where DATE(w1.`day_date`) = DATE(`weather`.`day_date`)
GROUP BY
DATE(`day_date`)
, `main_weather`
order by count(*) DESC
limit 1
) AS max_count_weather
, AVG(`temp`) AS av_temp
FROM `weather`
GROUP BY
DATE(`day_date`)
;
Try something like (untested):
select day_date, (select top 1 main_weather from MyTable t2 where date(t1.day_date) = date(t2.day_date) group by main_weather
order by count(*) desc) as Max_MainWeather, avg (temp) as AvgTemp
from MyTable t1
group by (day_date)
As far as I understand your problem (as it was not easy for me to understand), I came up with the following solution:
select t.on_date, t.main_weather, avg(temp) from
(select date(day_time) as on_date, main_weather, avg(temp) as avgtemp
from weather group by on_date,main_weather order by main_weather desc limit 1
) as t join weather on date(day_time)=t.on_date group by t.on_date;
The query is tested and works fine for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.