Power BI中日期MIN/MAX函数用途及活跃患者数DAX计算问题
Power BI每日活跃患者数计算问题及解决方案
问题背景
我是Power BI新手,需要绘制图表展示每日活跃患者数量。患者数据包含两个日期字段:
ReferralCreatedDate:转诊创建日期ServiceEndDate:服务结束日期(部分患者此字段为空,代表持续服务)
已通过Python实现需求,但Power BI中编写的DAX公式未得到正确结果,同时想了解Power BI中针对日期使用MIN/MAX函数的用途。
Python实现代码
import pandas as pd import matplotlib.pyplot as plt from datetime import datetime, timedelta # Convert date columns to datetime objects df['ReferralCreatedDate'] = pd.to_datetime(df['ReferralCreatedDate']) df['ServiceEndDate'] = pd.to_datetime(df['ServiceEndDate']) # Generate date range from January 1, 2021, till today start_date = datetime(2021, 1, 1) end_date = datetime.today() date_range = pd.date_range(start_date, end_date, freq='D') # Initialize an empty list to store active patient counts for each date active_patients_by_date = [] # Iterate through each date and calculate active patients for date in date_range: active_patients = df[ (df['ReferralCreatedDate'] <= date) & ((df['ServiceEndDate'] > date) | df["ServiceEndDate"].isnull()) ]['RequestNumber'].nunique() active_patients_by_date.append(active_patients) # Create a DataFrame for plotting plot_data = pd.DataFrame({'Date': date_range, 'Active Patients': active_patients_by_date}) # Plotting plt.plot(plot_data['Date'], plot_data['Active Patients'], marker='o') plt.xlabel('Date') plt.ylabel('Active Patients') plt.title('Active Patients Over Time') plt.xticks(rotation=45) plt.tight_layout() plt.show()
注:修正了原Python代码中的逻辑错误——原条件
df["ServiceEndDate"].notnull()应为df["ServiceEndDate"].isnull(),否则会错误排除无服务结束日期的持续服务患者。
原错误DAX公式
Active Patients = SUMX( FILTER( ALL('SDP_Patients'), 'SDP_Patients'[ReferralCreatedDate] <= SELECTEDVALUE('Total Patients Count'[Date]) && ( 'SDP_Patients'[ServiceEndDate] > SELECTEDVALUE('Total Patients Count'[Date]) || ISBLANK(SDP_Patients[ServiceEndDate]) ) ), CALCULATE(DISTINCTCOUNT('SDP_Patients'[RequestNumber])) )
修正后的DAX公式
方法一:直接使用CALCULATE + FILTER
Active Patients = VAR CurrentDate = SELECTEDVALUE('Total Patients Count'[Date]) RETURN CALCULATE( DISTINCTCOUNT('SDP_Patients'[RequestNumber]), FILTER( ALL('SDP_Patients'), 'SDP_Patients'[ReferralCreatedDate] <= CurrentDate && (ISBLANK('SDP_Patients'[ServiceEndDate]) || 'SDP_Patients'[ServiceEndDate] > CurrentDate) ) )
方法二:通过迭代唯一患者ID统计
Active Patients = VAR CurrentDate = SELECTEDVALUE('Total Patients Count'[Date]) VAR ActivePatients = FILTER( VALUES('SDP_Patients'[RequestNumber]), CALCULATE( MAX('SDP_Patients'[ReferralCreatedDate]) <= CurrentDate && (ISBLANK(MAX('SDP_Patients'[ServiceEndDate])) || MAX('SDP_Patients'[ServiceEndDate]) > CurrentDate) ) ) RETURN COUNTROWS(ActivePatients)
错误原因:原公式中
SUMX逐行迭代筛选后的患者表,每一行都执行一次DISTINCTCOUNT,导致同一个患者被多次累加,结果远大于实际值。
Power BI中MIN/MAX函数在日期场景的用途
- 获取日期范围边界:计算所有患者的最早转诊日期
MIN('SDP_Patients'[ReferralCreatedDate])或最晚服务结束日期MAX('SDP_Patients'[ServiceEndDate]),用于确定报表的时间范围。 - 统一患者时间维度:当同一个患者有多条记录时,用MIN/MAX获取该患者的首次转诊日期或末次服务日期,避免重复统计。
- 上下文日期筛选:在CALCULATE中配合筛选器,比如计算某个月内的最大服务结束日期,判断患者是否在该月内仍在服务。
- 时间智能函数配合:结合DATESBETWEEN等函数,用MIN/MAX定义时间区间的起止点,例如
DATESBETWEEN('Date'[Date], MIN('SDP_Patients'[ReferralCreatedDate]), TODAY())。
内容的提问来源于stack exchange,提问作者meharoo1
相关产品推荐
相关产品推荐

