我正在使用 SQL Server 并且我有下表 exampleTable
在我的数据库中:
我的目标是返回以下结果,其中我在附加列中有每组的平均值:
到目前为止我尝试了什么(错误,因为它不计算每组的平均值,而是计算所有列的总平均值):
SELECT
exampleGroup, exampleName, exampleValue,
(SELECT AVG(exampleValue) FROM exampleTable) AS averageExampleGroup
FROM exampleTable;
最佳答案
你只需要像这样使用 OVER()
子句:
SELECT
exampleGroup, exampleName, exampleValue,
AVG(exampleValue) OVER (PARTITION BY exampleGroup) AS GroupAvg
FROM exampleTable;
这会返回基于每个 exampleGroup
的平均值 作为结果集中的新列。
关于sql - 返回每行中每组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66612156/