简体   繁体   中英

How to do a rolling average in MySQL 8 with two variables?

I'm trying to figure out how to do a rolling average across both date and state.

The query below only gives an average of the positive increase of COVID cases, but not broken out by state.

I can't find any examples (sorry if I missed them) that extend the query logic below to do a rolling average by date + state.

Thanks in advance.

SELECT
    date,
    state,
    positiveIncrease,
    AVG( positiveIncrease ) OVER ( ORDER BY date DESC RANGE INTERVAL 3 DAY PRECEDING ) AS rolling_average 
FROM
    `covid-history` 
ORDER BY
    date DESC

Just add the state to the partition by clause of the window function:

AVG(positiveIncrease) OVER ( 
    PARTITION BY state      -- partition clause
    ORDER BY date DESC 
    RANGE INTERVAL 3 DAY PRECEDING 
) AS rolling_average

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM