如何使用DAX标记连续5天及以上的长期缺勤(LTA)日期?
Power Pivot DAX 实现连续5天缺勤(LTA)标记方案
前提假设
你的数据集(假设表名为Attendance)包含以下字段:
EmployeeID:员工标识(多员工场景必须,单员工可忽略)Date:考勤日期(确保每天唯一,无重复记录)Paid hours:当日应出勤工时Absence hours:当日缺勤工时
我们定义缺勤日为Absence hours等于Paid hours的全天缺勤日(可根据需求调整),连续5天及以上的缺勤周期内所有日期标记为LTA。
步骤1:创建缺勤日标记列
先判断每日是否为缺勤日,生成辅助列:
IsAbsent = // 可根据实际需求调整:比如只要有缺勤就标记,改为 IF(Attendance[Absence hours] > 0, 1, 0) IF(Attendance[Absence hours] = Attendance[Paid hours], 1, 0)
步骤2:计算连续缺勤周期长度
核心逻辑:找到当前日期所在连续缺勤周期的首尾日期,计算整个周期的天数,确保周期内所有日期都能获取到完整周期长度:
ContinuousAbsenceLength = VAR CurrentEmployee = Attendance[EmployeeID] VAR CurrentDate = Attendance[Date] VAR IsCurrentAbsent = Attendance[IsAbsent] // 找到当前连续缺勤周期的起始日期:往前第一个非缺勤日的次日 VAR CycleStart = CALCULATE( MAX(Attendance[Date]), FILTER( ALL(Attendance), Attendance[EmployeeID] = CurrentEmployee && Attendance[Date] < CurrentDate && Attendance[IsAbsent] = 0 ) ) + 1 // 找到当前连续缺勤周期的结束日期:往后第一个非缺勤日的前日 VAR CycleEnd = CALCULATE( MIN(Attendance[Date]), FILTER( ALL(Attendance), Attendance[EmployeeID] = CurrentEmployee && Attendance[Date] > CurrentDate && Attendance[IsAbsent] = 0 ) ) - 1 RETURN IF( IsCurrentAbsent = 1, // 计算周期总天数,处理周期在数据集首尾的情况 DATEDIFF( COALESCE(CycleStart, CurrentDate), COALESCE(CycleEnd, CurrentDate), DAY ) + 1, 0 )
步骤3:生成LTA标记列
根据连续缺勤周期长度判断是否标记为LTA:
IsLTA = IF(Attendance[ContinuousAbsenceLength] >= 5, "LTA", "Short Absence/Present")
优化方案(DAX 2020+ 支持窗口函数)
如果你的Power Pivot版本支持WINDOW函数,可使用更高效的窗口计算替代上述周期长度计算:
ContinuousAbsenceLength_Window = VAR CurrentEmployee = Attendance[EmployeeID] VAR CurrentRowRank = RANKX( FILTER(Attendance, Attendance[EmployeeID] = CurrentEmployee), Attendance[Date],,ASC,Dense ) // 往前查找第一个非缺勤行的排名 VAR PrevNonAbsentRank = MAXX( WINDOW(1, ABS, CurrentRowRank-1, REL, FILTER(Attendance, Attendance[EmployeeID] = CurrentEmployee)), IF(Attendance[IsAbsent] = 0, [CurrentRowRank], BLANK()) ) // 往后查找第一个非缺勤行的排名 VAR NextNonAbsentRank = MINX( WINDOW(CurrentRowRank+1, REL, -1, ABS, FILTER(Attendance, Attendance[EmployeeID] = CurrentEmployee)), IF(Attendance[IsAbsent] = 0, [CurrentRowRank], BLANK()) ) RETURN IF( Attendance[IsAbsent] = 1, COALESCE(NextNonAbsentRank, COUNTROWS(FILTER(Attendance, Attendance[EmployeeID] = CurrentEmployee))) - COALESCE(PrevNonAbsentRank, 0), 0 )
注意事项
- 确保
Date列无重复记录(同一员工同一天仅一条数据),否则会导致周期计算错误。 - 单员工场景下,可删除所有
CurrentEmployee相关的筛选条件,简化公式。 - 缺勤日的定义可根据实际业务调整,比如部分缺勤是否算入连续周期,修改
IsAbsent列的判断逻辑即可。
内容的提问来源于stack exchange,提问作者jpalmer0200
相关产品推荐
相关产品推荐

