如何在 Google 查询 (SQL) 中比较个人数据以聚合分组?

How to compare Individual data to aggregate group by in Google Query (SQL)?

我有一个这样的 table,当前 table 为蓝色,所需结果以黄色突出显示:

我的目标是使用内置的 =QUERY() 函数在 Google 表格中设置查询(注意:基于 Google 自己的查询语言,它与 SQL) 非常相似,后者基本上可以完成整个 table,而无需添加额外的公式。我知道如何以

这样的方式单独查找月平均值
SELECT month(DateRun), average(metric) GROUP BY month(DateRun)

但是你怎么能拥有它就像

SELECT AdID, DateRun, Metric, average(Metric for Associated Month), IndividualMetric - AverageForMonth 

我试图自己找到它,但未能找到我可以转换为自己使用的资源。

前阵子学习了子查询,感觉可能是这个问题的答案,但我很迷茫。

如果我可以提供任何其他信息,请告诉我。

您似乎在寻找 window 平均值:

select 
    AdID, 
    DateRun, 
    Metric, 
    avg(Metric) over(
        partition by Metric, date_trunc(DateRun, month)
    ) month_avg_metric,
    Metric - avg(Metric) over(
        partition by Metric, date_trunc(DateRun, month)
    ) diff_with_month_avg_metric
from mytable 

结果集中的最后一列为您提供当前月份的指标平均值,最后一列计算当前指标与其月平均值之间的差异。

尝试:

=ARRAYFORMULA(IFNA(VLOOKUP(MONTH(B2:B), 
 QUERY(B2:C, "select month(B)+1,avg(C) group by month(B)"), 2, 0)))

和:

=ARRAYFORMULA(IF(B2:B="",,C2:C-D2:D))


更新: