首页 > 解决方案 > 返回每行中每组的平均值

问题描述

我正在使用 SQL Server,我的exampleTable数据库中有下表:

示例组 示例名称 示例值
一种 名称1 100
名称2 500
C 名称3 300
名称4 700
一种 名称5 500
C 名称6 600

我的目标是返回以下结果,其中我在附加列中有每组的平均值:

示例组 示例名称 示例值 平均示例组
一种 名称1 100 300
一种 名称5 500 300
名称2 500 600
名称4 700 600
C 名称3 300 450
C 名称6 600 450

到目前为止我尝试了什么(错误,因为它不计算每组的平均值,而是计算所有列的总平均值):

SELECT 
    exampleGroup, exampleName, exampleValue,
    (SELECT AVG(exampleValue) FROM exampleTable) AS averageExampleGroup
FROM exampleTable;

标签: sqlsql-server

解决方案


使用 over()

select exampleGroup, exampleName, exampleValue,
  Avg(exampleValue) over(partition by exampleGroup) averageExampleGroup
from exampleTable

推荐阅读