我从控制风传感器的嵌入式设备填充了以下简单的 wind 表。
describe wind;
Field Type Null Key Default Extra
average float YES NULL
min float YES NULL
max float YES NULL
direction int(11) YES NULL
timestamp datetime YES NULL
方向是度,因此范围从0到360.
典型条目:
select * from wind order by timestamp desc limit 5;
average min max direction timestamp
7.34167 5.9 10.2 307 2018-04-26 10:24:07
6.655 4.2 8.9 301 2018-04-26 10:23:03
8.74667 7.2 10.8 307 2018-04-26 10:21:59
9.4925 7.4 10.7 295 2018-04-26 10:20:55
11.7175 8.6 14.2 306 2018-04-26 10:19:51
我想计算N,NNE等十六个风轴的平均风速分布。
基于此group by range in mysql,我能够进行分组。 (请注意,我不能使用'floor'解决方案,因为北区间为348.25-> 360和0-> 11.25)
我想我差不多了,但我找不到正确的语法来制作平均值(实际上按风向分组的AVG(平均值))。
这是我目前的代码:
select w.dir as `wind direction`, count(*) as `occurence`
from (
select CASE
when direction BETWEEN 11.25 and 33.75 then 'NNE'
when direction BETWEEN 33.75 and 56.25 then 'NE'
when direction BETWEEN 56.25 and 78.75 then 'ENE'
when direction BETWEEN 78.75 and 101.25 then 'E'
when direction BETWEEN 101.25 and 123.75 then 'ESE'
when direction BETWEEN 123.75 and 146.25 then 'SE'
when direction BETWEEN 146.25 and 168.75 then 'SSE'
when direction BETWEEN 168.75 and 191.25 then 'S'
when direction BETWEEN 191.25 and 213.75 then 'SSW'
when direction BETWEEN 213.75 and 236.25 then 'SW'
when direction BETWEEN 236.25 and 258.75 then 'WSW'
when direction BETWEEN 258.75 and 281.25 then 'W'
when direction BETWEEN 281.25 and 303.75 then 'WNW'
when direction BETWEEN 303.75 and 325.75 then 'NW'
when direction BETWEEN 325.75 and 348.25 then 'NNW'
else 'N'
end as `dir`
from wind) w
group by w.dir
我尝试添加
AVG(w.average) as `mean`
在第一行,但我收到错误#1054。我不确定如何包含平均列以便能够计算AVG。
奖金:我还有一个次要问题:分组是按字母顺序完成的,如下所示:
wind direction occurence
E 31
ENE 58
ESE 66
N 212
NE 128
NNE 62
NNW 326
NW 449
S 108
SE 133
SSE 192
SSW 355
SW 47
W 173
WNW 333
WSW 22
我想保留我的案例陈述的顺序(理想情况下,我喜欢North N案件是第一个)。
order by w.dir
做同样的事情,按字母排序。如何保持案件顺序?
非常感谢
答案 0 :(得分:2)
我认为此查询应该为您提供所需的结果(没有足够的样本数据)。基本上你只需要在子查询中选择平均值和方向,然后就可以得到你想要的平均值,你可以按原始方向编号排序(我们加上11.75并使其模数为360,使方向从0开始为N和NNW上升至359。
select w.dir as `wind direction`, round(avg(average),4) as mean, count(*) as `occurence`
from (
select CASE
when direction BETWEEN 11.25 and 33.75 then 'NNE'
when direction BETWEEN 33.75 and 56.25 then 'NE'
when direction BETWEEN 56.25 and 78.75 then 'ENE'
when direction BETWEEN 78.75 and 101.25 then 'E'
when direction BETWEEN 101.25 and 123.75 then 'ESE'
when direction BETWEEN 123.75 and 146.25 then 'SE'
when direction BETWEEN 146.25 and 168.75 then 'SSE'
when direction BETWEEN 168.75 and 191.25 then 'S'
when direction BETWEEN 191.25 and 213.75 then 'SSW'
when direction BETWEEN 213.75 and 236.25 then 'SW'
when direction BETWEEN 236.25 and 258.75 then 'WSW'
when direction BETWEEN 258.75 and 281.25 then 'W'
when direction BETWEEN 281.25 and 303.75 then 'WNW'
when direction BETWEEN 303.75 and 325.75 then 'NW'
when direction BETWEEN 325.75 and 348.25 then 'NNW'
else 'N'
end as `dir`,
average,
direction
from wind) w
group by w.dir
order by floor(w.direction + 11.75) mod 360