sql - 返回每行中每组的平均值
问题描述
我正在使用 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;
解决方案
使用 over()
select exampleGroup, exampleName, exampleValue,
Avg(exampleValue) over(partition by exampleGroup) averageExampleGroup
from exampleTable
推荐阅读
- python - 读取csv后pandas列中的不同类型
- java - WildFly 性能
- python-3.x - XCOM 不适用于 PythonVirtualenvOperator 气流 1.10.6
- ruby-on-rails - 我无法创建删除喜欢的功能
- java - Java设计——抽象类声明实例讲解
- sql - PostgreSQL 多重连接
- javascript - 为什么我的代码失败了?试图用基本的替换箭头表达式
- r - R ggseasonplot:突出显示当前年份
- android - 头部粗尾部细的圆形进度条粗细
- python - 如何在 Python 中按顺序将列表元素添加到另一个列表?