mysql 按月累计平均值,2个变量

balp4ylt  于 2023-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(136)

我有两个专栏:洗涤评分(wash_sc)和农业评分(agric_sc)。我想得到累计和按月分组的平均值。
目前,我能够对一个变量完成此操作,尽管返回响应需要很长时间:

select date_format(s1.createdAt,'%b-%Y') as month, 
    (
       select AVG(s2.wash_sc) 
       from checkins s2 
       where s2.createdAt <= last_day(s1.createdAt)
    ) as total 
from checkins s1 
group by month 
order by s1.createdAt;

我怎样才能做到这一点(更快!)对于两列?

xqk2d5yq

xqk2d5yq1#

根据您确认要实现运行平均值,根据您自己的查询,您需要根据运行总和除以运行计数进行计算:

select year(createdAt) as `year`, month(createdAt) as `month`,
  sum(sum(wash_sc)) over w / sum(count(wash_sc)) over w as cumul_avg_wash_sc,
  sum(sum(agric_sc)) over w / sum(count(agric_sc)) over w as cumul_avg_agric_sc
from checkins
group by year(createdAt), month(createdAt)
window w as (order by year(createdAt), month(createdAt));

sum(sum(wash_sc)) over w使用SUM()作为window function来产生每组内部SUM(wash_sc)的累积和。累积计数也是如此。
给定以下数据:
| 创建于|洗涤液|农业sc|
| - -----|- -----|- -----|
| 2019 -01- 21 00:00:00|十一|2|
| 2019 -01- 22 00:00:00|九个|4|
| 2019 -01- 23 00:00:00|七个|六|
| 2019 -01- 24 00:00:00| 5个|八|
| 2019 -01-05 00:00:00| 3|十个|
| 2019 -01- 16 00:00:00| 1|十二岁|
它输出:
| 年|月|积云洗涤sc|累积农业土壤|
| - -----|- -----|- -----|- -----|
| 二〇二一|1|一万一|两万|
| 2022| 1|六千|七万|
这里有一个db<>fiddle来玩。

tquggr8v

tquggr8v2#

SELECT 
    DATE_FORMAT(s1.createdAt, '%b-%Y') AS month,
    (SELECT SUM(s2.wash_score) FROM checkins s2 WHERE MONTH(s2.createdAt) <= MONTH(s1.createdAt)) AS cumulative_wash_score,
    (SELECT SUM(s3.agric_score) FROM checkins s3 WHERE MONTH(s3.createdAt) <= MONTH(s1.createdAt)) AS cumulative_agric_score
FROM 
    checkins s1
GROUP BY 
    MONTH(s1.createdAt)
ORDER BY 
    s1.createdAt;
xuo3flqw

xuo3flqw3#

你可以使用窗口函数AVG()

with cte as (
  select *, AVG(wash_sc) over (partition by YEAR(createdAt), MONTH(createdAt) order by createdAt) as cumul_wash_sc,
            AVG(agric_sc) over (partition by YEAR(createdAt), MONTH(createdAt) order by createdAt) as cumul_agric_sc
  from checkins
)
select date_format(createdAt,'%b-%Y') as month, max(cumul_wash_sc) as cumulative_wash_score, max(cumul_agric_sc) as cumulative_agric_score
from cte
group by date_format(createdAt,'%b-%Y')

相关问题