PowerBI条件列:判断客户是否在上月存在订单记录
在Power BI中添加判断客户上月是否有订单的自定义列
方法1:Power Query编辑器(M语言)实现
适合在数据加载前的查询阶段处理,步骤如下:
- 打开Power Query编辑器,选中目标数据集
- 添加自定义列,粘贴以下M语言代码:
let currentDate = [Date], currentMonth = Date.Month(currentDate), currentYear = Date.Year(currentDate), prevMonthStart = if currentMonth = 1 then #date(currentYear-1, 12, 1) else #date(currentYear, currentMonth-1, 1), prevMonthEnd = Date.EndOfMonth(prevMonthStart), customer = [Customer_Number], hasOrderPrevMonth = List.Contains(Table.SelectRows(Source, each [Customer_Number] = customer and [Date] >= prevMonthStart and [Date] <= prevMonthEnd)[Customer_Number], customer) in if hasOrderPrevMonth then 1 else 0
注意:将代码里的
Source替换为你实际的数据集名称(可在Power Query左侧查询面板查看)
- 点击确定,即可生成
In_prev_month列
代码说明
prevMonthStart/prevMonthEnd:计算当前行日期对应的上月起始、结束日期Table.SelectRows:筛选出同一客户、日期在上月范围内的记录List.Contains:判断是否存在符合条件的记录,将布尔值转为1或0
方法2:DAX计算列实现
如果需要在数据模型中添加计算列,使用以下DAX公式:
In_prev_month = VAR CurrentDate = '你的表名'[Date] VAR PrevMonthStart = EOMONTH(CurrentDate, -2) + 1 VAR PrevMonthEnd = EOMONTH(CurrentDate, -1) VAR Customer = '你的表名'[Customer_Number] VAR HasOrder = CALCULATE( COUNTROWS('你的表名'), '你的表名'[Customer_Number] = Customer, '你的表名'[Date] >= PrevMonthStart, '你的表名'[Date] <= PrevMonthEnd ) > 0 RETURN IF(HasOrder, 1, 0)
替换公式里的
你的表名为实际表名称
验证结果
生成的列与示例一致:
| Customer_Number | Date | In_prev_month |
|---|---|---|
| C1 | 01.01.2022 | 0 |
| C2 | 01.01.2022 | 0 |
| C3 | 01.01.2022 | 0 |
| C2 | 01.02.2022 | 1 |
| C3 | 01.02.2022 | 1 |
| C4 | 01.02.2022 | 0 |
内容的提问来源于stack exchange,提问作者user9092346
相关产品推荐
相关产品推荐

