按项目类型计算价格和分组的加权平均值

时间:2016-07-13 14:03:50

标签: sql ms-access

我在Access中有一个表格,用于跟踪每个商店的某些产品的价格。该表如下所示:

Date     | Store   | Item      | SalesPounds | CompanyPrice
1/1/2016 | Store A | Product A | 1,000       | $5.00
1/1/2016 | Store A | Product B | 2,000       | $4.65
1/1/2016 | Store B | Product A | 5,000       | $7.56
1/1/2016 | Store B | Product B | 3,000       | $1.65

我想计算CompanyPrice的加权平均值,然后按产品对它们进行分组,看起来像这样:

Date     |Item      | SalesPounds  | CompanyPrice
1/1/2016 | Product A | 6,000        |$7.13
1/1/2016 | Product B | 5,000        |$2.85

我目前使用的查询是

SELECT [Date], [Item], Sum([SalesPounds]) as SumOfPounds, Sum([CompanyPrice]) as SumOfPrice
FROM MyTableName
GROUP BY [Date], [Item];

1 个答案:

答案 0 :(得分:1)

以下查询应计算加权平均值:

SELECT [Date],
       Sum([SalesPounds]*[CompanyPrice]) / Sum([SalesPounds]) as WeightedAvg
FROM MyTableName
GROUP BY [Date];