在powerbi中,earlier是个很神奇的函数,也是很让人头脑发晕的函数。
它让人发晕的地方有两个:
一是如果不能深刻理解上下文,就无法理解它的运作原理;
二是它主要用于计算列,如果一不小心将其用到了度量值上,就很可能出错;
比如这个帖子的标题【EARLIER/EARLIEST 引用不存在的更早的行上下文】(对应的英文是“EARLIER/EARLIEST refer to an earlier row context which doesn’t exist.” ),就是没注意把earlier用到度量值之上:
= SUMX(FILTER('Data','Data'[订单日期]>EARLIER('Data'[订单日期])),[金额])
出现的错误提示:
EARLIER/EARLIEST 引用不存在的更早的行上下文
最开始我完全没意识到自己在度量值上操作,爬网半天也没查出个所以然来。后来爬官网才发现自己一直忽视了earlier的应用环境:
EARLIER is mostly used in the context of calculated columns.
那么,earlier是不是就不能用在度量值上呢,也可以,但是有一个前提条件:
If we really want to use EARLIER as part of a measure, we must introduce nested iterations of row context that interact with each other. In other words, the evaluation must happen for each row.
翻译过来就是:
如果我们想在度量值中使用earlier,就必须在嵌套迭代中使用行上下文。也就是说,必须对每一行进行计算。
为什么会这样呢?
原因在于:
FILTER evaluates first, and by the time SUMX’s row context is being evaluated FILTER has already returned a table, hence the two contexts do not interact with each other. In that sense, EARLIER cannot be used.【filter函数会首先进行计算,由于这两个上下文彼此不进行交互,当sumx进行计算的时候filter已经返回了一个table了。在这种情况下,earlier就不能运行。
具体请参见《Can EARLIER be used in DAX measures?》
如果确实要把earlier用在度量值上,那么最开始我写的那个度量值应改造为:
= CALCULATE(SUM(Data[金额]),FILTER(Data,SUMX(FILTER('Data','Data'[订单日期]>EARLIER('Data'[订单日期])),[金额])))
网友评论