首页 > 解决方案 > 不同表中两列的加权平均值

问题描述

我有一张名为的桌子Products和另一张名为Sales. 它们由 相关ProductId。我需要在Products表格中找到选定产品列表的加权平均值。公式是

(Product1.UnitCost * Sales[ProductId1].ItemsSold +
 Product2.UnitCost * Sales[ProductId2].ItemsSold + ...) /
(Total sum of the chosen products items sold)

我该如何为此编写 DAX 公式?

Products
			
ProductId   |	Name  |	Description   |	UnitItemCost
------------|---------|---------------|----------------
id1	    |	Name1 |	Description1  |	10
id2	    |	Name2 |	Description2  |	20
id3	    |	Name3 |	Description3  |	30
			
			
Sales	
		
ProductId  |	ItemsSold
-----------|--------------		1714.126984
Id1	   |	20		
id2	   |	30		
id1	   |	10		
id2        |    40		
id3	   |	50		
id3	   |	39		

Average unit cost = 23.12    (10*30+20*70+30*89)/189

标签: dax

解决方案


我不确定您上面示例中的逻辑。看起来您正在尝试UnitCost * ItemSold为每种产品取值,将它们加在一起并除以 total ItemSold

那应该((10*30)+(20*70)+(30*89)) = 4370除以189,即23.12

如果是这种情况,您可以像这样创建一个计算度量:

Average unit cost = 
--create a summary table, one row per product id, with a 'Cost * Sold' column giving you UnitItemCost * ItemSold for each product
VAR my_table =
    SUMMARIZE (
        Sales,
        Sales[ProductId],
        "Cost * Sold", MAX ( Products[UnitItemCost] ) * SUM ( Sales[ItemSold] )
    )
RETURN

--take the sum of UnitItemCost * ItemSold for each product (4370 in your example) divided by the total ItemSold (189 in your example) 
    SUMX ( my_table, [Cost * Sold] ) / SUM ( Sales[ItemSold] )

只要您的 Products 和 Sales 表通过 ProductId 关联,这应该可以工作。在我用你的样本数据测试它之后,我得到了 23.12。


推荐阅读