簡體   English   中英

如何編寫SQL查詢以計算三個連續值的平均值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM