[英]How to write an SQL query to calculate the average for three consecutive values?
我有这样的桌子
userID time NoOfVisits
1 2014 50
2 2015 60
3 2016 70
4 2017 80
5 2018 90
6 2019 100
我需要编写一个sql查询,该查询将显示特定站点的时间和过去3年NoOfVisits的平均值。
输出应为
userID time NoOfVisits
1 2014 50.0000
2 2015 55.0000
3 2016 60.0000
4 2017 70.0000
5 2018 80.0000
6 2019 90.0000
说明:
对于用户ID 6(80 + 90 + 100)/3=90.0000
请帮我解决这个问题。
您可以使用MySQL 8+中提供的累积平均值:
select t.*,
avg(visits) over (order by time rows between 2 preceding and current row) as avg_visits_3
from t;
假设年份之间没有间隔(例如您的样本数据),则可以自行加入表并按group by userid, time
进行group by userid, time
以获取平均值:
select
t.userid, t.time, avg(tt.noofvisits) NoOfVisits
from tablename t inner join tablename tt
on tt.time between t.time - 2 and t.time
group by t.userid, t.time
参见演示 。
结果:
| userid | time | NoOfVisits |
| ------ | ---- | ---------- |
| 1 | 2014 | 50 |
| 2 | 2015 | 55 |
| 3 | 2016 | 60 |
| 4 | 2017 | 70 |
| 5 | 2018 | 80 |
| 6 | 2019 | 90 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.