[英]SQL - return rows for values with MAX COUNT
我想访问一个天气表并将其按天和月求和。 我希望某些值是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`;
对于第二个示例,查询仅返回一行,因为您已添加了LIMIT 1
选项。 其余的,我不太了解您对要获得的结果的描述,所以我无能为力。 举一个带有几行数据的小例子,这样人们就可以理解您要实现的目标,这没有什么坏处。
看起来相关的子查询可以做到,但是不能确定它的扩展程度。
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`)
;
尝试类似(未试用)的方法:
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)
据我了解您的问题(因为我不容易理解),我提出了以下解决方案:
从中选择t.on_date,t.main_weather,avg(temp)
(选择date(day_time)作为on_date,main_weather,avg(temp)作为avgtemp
来自天气组(按on_date,main_weather顺序,按main_weather desc限制1)
)作为t加入天气on date(day_time)= t.on_date group by t.on_date;
该查询已经过测试,对我来说效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.