在SQL中获得平均值

时间:2014-04-21 14:19:24

标签: sql sql-server-2008

我基本上试图获得列的平均值。所以我需要列的总和(Erosion12)除以返回的总行数(count(BrandDescAbbr)。下面是我的代码,但它似乎没有工作。

declare @g table (GenProdIdent varchar(50) primary key )
insert @g
values ('44505080000310'),('44505080000320')

select BrandDescAbbr,
           12 as [Month],
           Erosion12 as Erosion,
           avg(Erosion12)
      from ErosionData2
     where GenProdIdent in (select GenProdIdent from @g)
  group by BrandDescAbbr,
           Erosion12

1 个答案:

答案 0 :(得分:0)

Erosion12

取出分组
select BrandDescAbbr,
           12 as [Month],
           /*Erosion12 as Erosion,*/
           avg(Erosion12)
      from ErosionData2
     where GenProdIdent in (select GenProdIdent from @g)
  group by BrandDescAbbr
           /*, Erosion12*/

Erosion12分组时,所有记录的值都相同,因此平均值无意义。

或者,如果您需要所有单独的Erosion12,则组内的平均值使用窗口函数:

select BrandDescAbbr,
           12 as [Month],
           Erosion12 as Erosion
           AVG(Erosion12) OVER (PARTITION BY BrandDescAbbr)
      from ErosionData2
     where GenProdIdent in (select GenProdIdent from @g)