Power BI DAX去年累计求和错误修复请求(含闰年问题)
Power BI同比KPI累计度量值修复方案
现有Power BI报表用于统计年度初至对应年度当前日期的同比KPI,需制作展示每周KPI汇总历史的表格可视化组件。目前以下三个DAX度量值计算正确:
Receipts this yearReceipts this year (cumulative)Receipts last year
但Receipts last year (cumulative)存在逻辑错误:由于2024年2月29日的交易无对应2025年日期,导致该周累计值少统计14笔交易(正确值应为143,当前计算结果为129)。需修改该累计度量值,确保能正确对Receipts last year的输出结果求和。
现有DAX代码
日历表(Calendar)
Calendar = var _calendar = CALENDAR("1/1/2019", DATE(YEAR(TODAY())+3, 12, 31)) RETURN ADDCOLUMNS( _calendar, "ISO Week Number", WEEKNUM([Date],2) ,"Saturday's Date", [Date] + (5 - WEEKDAY([Date],3)) )
本年收款(Receipts this year)
Receipts this year = VAR __date_max = MAXX(ALL('Calendar'), [Date].[Date]) VAR __date_min = DATE(YEAR(TODAY()), 1, 1) RETURN CALCULATE( DISTINCTCOUNT('InventoryTable'[transaction number]) ,FILTER( 'Calendar' ,[Date].[Date] >= __date_min && [Date].[Date] < __date_max ) ,FILTER( 'InventoryTable' ,[Transaction Type] IN {"Inbound 1","Inbound 2"} ) )
本年累计收款(Receipts this year (cumulative))
Receipts this year (cumulative) = VAR CurrentDate = MAX('InventoryTable'[Date]) RETURN CALCULATE( DISTINCTCOUNT('InventoryTable'[transaction number]), FILTER( ALLSELECTED('InventoryTable'), 'InventoryTable'[Date] <= CurrentDate && YEAR('InventoryTable'[Date]) = YEAR(TODAY()) ) ,'InventoryTable'[Transaction Type] IN {"Inbound 1","Inbound 2"} )
上年收款(Receipts last year)
Receipts last year = CALCULATE( DISTINCTCOUNT('InventoryTable'[transaction number]) ,DATEADD('Calendar'[Date],-1,YEAR) ,'Calendar'[Date] <= TODAY()-365 ,'InventoryTable'[Transaction Type] IN {"Inbound 1","Inbound 2"} )
错误的上年累计收款(Receipts last year (cumulative))
Receipts last year (cumulative) = VAR __calc = CALCULATE( SUMX( FILTER( ALLSELECTED('Calendar') ,[Saturday's Date] <= MAX('Calendar'[Saturday's Date]) --&& [Date] <= TODAY() ) ,[Receipts last year] ) ) RETURN IF( SELECTEDVALUE('Calendar'[Saturday's Date]) <= TODAY() ,__calc ,BLANK() )
修复方案及修改后的代码
问题原因
原累计度量值在过滤日历表时,依赖Date字段的DATEADD映射,导致2024年2月29日(闰日)对应的2025年日期不存在,该日的Receipts last year无法被纳入对应周的累计计算。正确的思路应基于**周维度(Saturday's Date)**来累计,确保每个周的Receipts last year结果都被完整求和。
修改后的上年累计收款度量值
Receipts last year (cumulative) = VAR CurrentWeekEnd = MAX('Calendar'[Saturday's Date]) VAR LastYearWeeks = FILTER( ALLSELECTED('Calendar'), -- 筛选上年对应周及之前的所有周 [Saturday's Date] <= CurrentWeekEnd - 364 && -- 用364天(52周)替代365,适配闰年 [Saturday's Date] >= DATE(YEAR(CurrentWeekEnd)-1, 1, 1) ) RETURN IF( CurrentWeekEnd <= TODAY(), SUMX(LastYearWeeks, [Receipts last year]), BLANK() )
代码说明
- CurrentWeekEnd:获取当前可视化上下文的周结束日期(周六)。
- LastYearWeeks:筛选出上年对应周及之前的所有周,使用
-364天(52周)替代-365天,避免闰年日期偏移问题,同时确保只包含上年年度初之后的周。 - SUMX:遍历筛选后的上年周集合,对每个周的
Receipts last year结果求和,确保闰日所在周的交易数据被正确累计。
内容的提问来源于stack exchange,提问作者LT_AKR
相关产品推荐
相关产品推荐

