我使用的是SQL Server,我的数据库中有下表exampleTable
:
exampleGroup | exampleName | exampleValue|
---|---|---|
A | 名称1 | 100 |
B | 名称2 | 500 |
C | 名称3 | 300 |
B | 名称4 | 700 |
名称5 | 500 | |
C | 名称6 | 600 |
您只需要像这样使用OVER()
子句:
SELECT
exampleGroup, exampleName, exampleValue,
AVG(exampleValue) OVER (PARTITION BY exampleGroup) AS GroupAvg
FROM exampleTable;
这将返回基于每个exampleGroup
的平均值,作为结果集中的新列。
使用over((
select exampleGroup, exampleName, exampleValue,
Avg(exampleValue) over(partition by exampleGroup) averageExampleGroup
from exampleTable
如果您想要每个组的平均值,那么您需要将行限制在特定的组中。换句话说,您需要用where
来限定SELECT AVG(...
。
SELECT e1.exampleGroup
,e1.exampleName
,e1.exampleValue
,(SELECT AVG(e2.exampleValue)
FROM exampleTable e2
where e2.exampleGroup = e1.exampleGroup) AS averageExampleGroup
FROM exampleTable e1;