将 FILTER 与 VALUES 一起使用(多行错误)

Using FILTER with VALUES (multiple rows error)

我正在为 DAX 权威指南一书提供的 Contoso 数据库学习 DAX。

我试图了解过滤器上下文,我写了这个度量:

CountColor:= COUNT ( 'Product'[Color] )

我将其放入数据透视表 table,其中 'Product'[Color] 添加到行部分,结果如下:

Row Labels CountColor
Azure 14
Black 602
Blue 77
... ...

这表明每行中的过滤器上下文由该行的颜色定义。

当我编写以下度量时,我预计 VALUES 仅 return 数据透视表行中当前可用的一种颜色的唯一值 table 并且它会自动获取转换为标量值:

CountColorValues:= CALCULATE (
                     COUNT ( 'Product'[Color] ),
                     FILTER ( 'Product',
                              'Product'[Color] = VALUES ( 'Product'[Color] )
                     )
                   )

但是将此度量设置为相同 table,我得到错误: “度量 'Product'[CountColorValues] 中的计算错误:在需要单个值的地方提供了多个值的 table。”

我创建了另一个度量来测试 VALUES 是否真的 return 单个值:

CountrowsValues:= COUNTROWS ( 
                     CALCULATETABLE ( VALUES ( 'Product'[Color] )
                     )
                  )

结果:

Row Labels CountrowsValues
Azure 1
Black 1
Blue 1
... ...

当我试图让 VALUES 在 FILTER 中工作时,我错过了什么?

在本例中,VALUES 获得了不同的项目列表,因此在以下情况中:

CountColorValues:= CALCULATE (
                     COUNT ( 'Product'[Color] ),
                     FILTER ( 'Product',
                              'Product'[Color] = VALUES ( 'Product'[Color] )
                     )
                   )

'Product'[Color] 试图等于 {'Azure', 'Black' , 'Blue'} 的列表,因此实际上您正在尝试制作行'Azure' 等于 table 个不同值

为此,需要将其更改为 IN,即列表中的 [color] 值,不等于列表。

 CountColorValues:= CALCULATE (
                         COUNT ( 'Product'[Color] ),
                         FILTER ( 'Product',
                                  'Product'[Color] IN VALUES ( 'Product'[Color] )
                         )
                       )

该问题可能是由枢轴 table 的 总计 引起的。 那里的上下文不同,不存在滤色器,因此每种颜色 VALUES returns,因此该度量给出了提到的多行错误。

关闭枢轴上的总计 table 并不能解决问题,错误不断出现。

结论是,即使您愿意抑制它,您也必须编写与总计兼容的度量。