mysql 在SQL中计算每月滚动/移动平均值

4c8rllxm  于 2022-12-17  发布在  Mysql
关注(0)|答案(1)|浏览(373)

我试图计算一组数据的月移动平均值。我有以下代码和示例数据

SELECT DDA_Account, Current_Balance, Date_Last_Updated,
ROUND(AVG(Current_Balance) OVER (PARTITION BY DDA_Account ORDER BY Date_Last_Updated RANGE INTERVAL 30 DAY preceding),2) as avg_current_balance
FROM trb_acct_3
WHERE DDA_Account = '3921'
ORDER BY Date_Last_Updated ASC;

在Excel代码片段中,您可以看到我是如何尝试取某个特定月份内所有日期的平均值的,例如在该月的第一天(或值可用的月份的第一天),平均值就是当前余额列中的值。第二天取当天和前一天的值的平均值。此操作将持续到该月的所有天,在每个月的开始重置(或者在数据可用的月份的第一天)。我将如何修复代码,以便在计算平均值时只考虑特定月份的天数?我认为使用RANGE会起作用,但我发现它不够具体。任何帮助都将不胜感激。

toiithl6

toiithl61#

要在每月初重置,窗口函数over (partition by dad_account, year-month order by date_last_updated)

with cte_acct as (
select dda_account,
       date_format(date_last_updated,'%Y-%m') as yr_mo,
       date_last_updated,
       current_balance
  from trb_acct_3)
select dda_account,
       yr_mo,
       date_last_updated,
       current_balance,
       round(avg(current_balance) over (partition by dda_account, yr_mo order by date_last_updated),2) as moving_avg
  from cte_acct
 order by date_last_updated;
 order by date_last_updated;

相关问题