database - 用于计算 PowerBI 中收入损失的 DAX 代码
问题描述
我有一个名为mytable的表,其中包含相关列:customer_id、amount、year。
我想计算连续 2 年之间的总收入损失。
我的伪代码想法是:
- 查找今年花费任何金额的客户
- 查找去年花费任何金额的客户
- 使用 1. 和 2 的列表查找去年消费但今年没有消费的客户。
- 合计这些客户的所有金额
我尝试编写以下 DAX 代码,但最后无法计算总和,出现语法错误。
lost revenues =
VAR current_customers = DISTINCT(CALCULATETABLE(VALUES('mytable'[customer_id]), 'mytable'[year]=2020))
VAR old_customers = DISTINCT(CALCULATETABLE(VALUES('mytable'[customer_id]), 'mytable'[year]=2019))
VAR lost_customers = EXCEPT(old_customers, current_customers)
VAR computed = CALCULATETABLE(VALUES('mytable'[amount]), 'mytable'[year]=2019, 'mytable'[customer_id] IN lost_customers)
RETURN SUM(computed[amount])
我也尝试了另一个计算值的版本,但它是错误的:
lost revenues =
VAR current_customers = DISTINCT(CALCULATETABLE(VALUES('mytable'[customer_id]), 'mytable'[year]=2020))
VAR old_customers = DISTINCT(CALCULATETABLE(VALUES('mytable'[customer_id]), 'mytable'[year]=2019))
VAR lost_customers = EXCEPT(old_customers, current_customers)
RETURN SUMX(lost_customers, CALCULATE(SUM('mytable'[amount])))
我究竟做错了什么?
编辑:
这是数据的最小示例。如您所见,客户 3 在 2020 年没有花费任何金额,因此损失的收入是他在 2019 年花费的总和(197 美元):
解决方案
假设您表中的所有字段都是Whole Numbers
,我创建了一个度量来计算LostRevenue
缺失年份的 ,并分配去年作为结果。
我创建了一个表DimYear
来拥有一个独特的年份列表,独立于原始TABLE
.
计算:测量
LostRevenue =
VAR SelectedCustomer =
SELECTEDVALUE ( 'Table'[customer] )
VAR SelectedYear =
SELECTEDVALUE ( DimYear[year] )
VAR AllCustomers =
SUMMARIZE ( 'Table', 'Table'[customer], 'Table'[year] )
VAR AllCombinations =
CALCULATETABLE (
CROSSJOIN ( { SelectedCustomer }, DISTINCT ( 'Table'[year] ) ),
REMOVEFILTERS ( 'Table'[customer] )
)
VAR MissingYears =
EXCEPT ( AllCombinations, AllCustomers )
VAR GetYear =
SUMMARIZE ( MissingYears, [year] )
VAR LastYearData =
CALCULATE (
SUM ( 'Table'[amount] ),
FILTER ( ALLSELECTED ( DimYear ), [year] = SelectedYear - 1 )
)
RETURN
IF ( SelectedYear IN GetYear, LastYearData, BLANK () )
关系
已创建新表
DimYear =
DISTINCT('Table'[year])
输出
表参考:TABLE
顾客 | 数量 | 年 |
---|---|---|
1 | 10 | 2019 |
2 | 43 | 2019 |
3 | 23 | 2019 |
1 | 10 | 2019 |
3 | 76 | 2019 |
2 | 5 | 2019 |
1 | 10 | 2019 |
2 | 10 | 2019 |
1 | 55 | 2019 |
1 | 10 | 2019 |
3 | 98 | 2019 |
1 | 15 | 2020 |
2 | 40 | 2020 |
1 | 18 | 2020 |
1 | 15 | 2020 |
2 | 7 | 2020 |
1 | 6 | 2020 |
2 | 7 | 2020 |
1 | 44 | 2020 |
1 | 15 | 2020 |
推荐阅读
- android - 使用 Hilt 提供首选项数据存储
- python - 拟合 matplotlib 直方图会产生不好的结果(并且只有 2 个参数)
- pyqt5 - PyQt5:为图形场景中的项目设置坐标
- python - Rasa NLU 在线和训练版问题
- reactjs - 我在 React 中使用道具时出现错误无法读取未定义的属性“地图”
- java - 从使用不同时区的日期计算时间
- c++ - c ++“错误:传递'const std :: vector
' 因为 'this' 参数丢弃了限定符 [-fpermissive]" - scala - 在构造函数的另一个参数的类型中引用依赖于路径的参数类型
- assembly - 为什么 rcx 在输入新标签时会刷新?
- kotlin - Kotlin,我怎样才能在这个意大利面条代码中缩短我的代码?