DAX同比对比需求:实现与今年同期而非整月的去年销售计数对比
Great question—this is a super common pain point when working with time intelligence in Power BI/DAX, especially when dealing with partial periods like your 2018 January data (only up to the 16th). Let's break down how to fix this.
The Root of the Problem
Your original PY Sales Count uses SAMEPERIODLASTYEAR, which works perfectly for full periods but fails here because it returns the entire matching period from last year (all of January 2017) instead of matching the exact date range of your incomplete current period (January 1–16, 2018).
The Solution: Match Exact Date Ranges
We need to create a measure that dynamically captures the exact date range of your current data, then maps that range to the same dates in the previous year. Here are two robust approaches:
Approach 1: Dynamic Date Range Mapping (Most Flexible)
This method works for any date range (days, weeks, partial months, etc.) by converting each date in your current context to its equivalent in the prior year:
PY Sales Count := VAR CurrentDateRange = DATESBETWEEN(dCalendar[Dates], MIN(dCalendar[Dates]), MAX(dCalendar[Dates])) VAR PriorYearDateRange = SELECTCOLUMNS( CurrentDateRange, "PriorYearDate", DATE(YEAR([Dates]) - 1, MONTH([Dates]), DAY([Dates])) ) RETURN CALCULATE([Sales Count], PriorYearDateRange)
How It Works:
CurrentDateRangegrabs all dates in your current filter context (e.g., Jan 1–16, 2018)PriorYearDateRangeconverts each of those dates to the same day/month in the prior year (Jan 1–16, 2017)CALCULATEruns your originalSales Countmeasure against this filtered prior year range
Approach 2: Partial Month Specific (Simpler for Monthly Views)
If you only need this for partial months, you can explicitly calculate the start and end dates of the prior year's matching partial period:
PY Sales Count (Partial Month) := VAR CurrentMaxDate = MAX(dCalendar[Dates]) VAR PriorYearEndDate = DATE(YEAR(CurrentMaxDate) - 1, MONTH(CurrentMaxDate), DAY(CurrentMaxDate)) VAR PriorYearStartDate = DATE(YEAR(PriorYearEndDate), MONTH(PriorYearEndDate), 1) RETURN CALCULATE( [Sales Count], DATESBETWEEN(dCalendar[Dates], PriorYearStartDate, PriorYearEndDate) )
How It Works:
CurrentMaxDategets the last date with data in your current context (Jan 16, 2018)PriorYearEndDatecalculates the same day/month in the prior year (Jan 16, 2017)PriorYearStartDatesets the start of the prior year's month (Jan 1, 2017)CALCULATEfilters the prior year to Jan 1–16, 2017 and runs your sales count
Testing the Measure
When you select January 2018 in your report, both measures will return sales counts from only January 1–16, 2017 instead of the entire month, perfectly aligning with your current period's data.
内容的提问来源于stack exchange,提问作者Dries Weytjens

