我想访问一张天气表,并按日期和月份对其进行评估。我想要一些值是AVG,一些是SUM。
我想用来自代表最大数量的集合数据的值来支持结果记录,但在几个组合之后,我还没有管理它。
示例数据:
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
通缉结果:
DATE(day_date) MAX(COUNT(main_weather) AVG(temp)
2012-01-01 Sunny 12.8
这是我的第一个显示我要做的事情的SQL:
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`;
答案 0 :(得分:0)
对于第二个示例,查询只返回一行,因为您添加了选项LIMIT 1
。对于其他人,我真的不明白你对结果的描述,所以我无法帮助你。给出一些带有几行数据的小例子,这样人们就可以理解你想要达到的目标,这不会有什么坏处。
答案 1 :(得分:0)
看起来相关的子查询可以做到这一点,但不确定它的扩展程度。
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`)
;
答案 2 :(得分:0)
尝试类似(未经测试)的内容:
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)
答案 3 :(得分:0)
据我了解你的问题(因为我不容易理解),我提出了以下解决方案:
从中选择t.on_date,t.main_weather,avg(temp)
(选择日期(day_time)为on_date,main_weather,avg(temp)为avgtemp
来自天气组的on_date,main_weather按main_weather desc limit 1的顺序排序
)作为t加入天气(day_time)= t.on_date group by t.on_date;
查询经过测试,对我来说很好。