powerbidaxdaxstudio

DAX calculate relatively last month, quarter and year


I need to create 3 measures for distinct count of MerchantName in DimMerchant for last month, last 3 months, and last year of a given relative date.

Example:

For DateValue = 4/1/2024 (date type MMddyyyy)

LM: count of merchants in 3/1/2024

L3M: count of merchants in 3/1/2024, 2/1/2024 and 1/1/2024

LY: count of merchants between 3/1/2024 and 4/1/2024

enter image description here

MerchantInternal# measure (current attempt):

CALCULATE(
    DISTINCTCOUNTNOBLANK('DimMerchant'[MerchantName]),
    FactTransaction
)

Table relationships:

enter image description here

Example data input for testing:

  1. DimDate (one to many to FactTransaction on DatePK)
DatePK DateValue Year Month
20230901 9/1/2023 2023 9
20231001 10/1/2023 2023 10
20231101 11/1/2023 2023 11
20231201 12/1/2023 2023 12
20240101 1/1/2024 2024 1
20240201 2/1/2024 2024 2
20240301 3/1/2024 2024 3
20240401 4/1/2024 2024 4
20240501 5/1/2024 2024 5
  1. DimMerchant (one to many to FactTransaction on MerchantHK)
MerchantHK MerchantName
AAA NAAA
AAA NAAA
BBB NBBB
DDD NDDD
BBB NBBB
DDD NDDD
CCC MCCC
DDD MDDD
BBB MBBB
  1. FactTransaction (Main fact table where DimDate and DimMerchant have relationship)
DatePK MerchantHK
20230901 AAA
20231001 AAA
20231101 BBB
20231201 DDD
20240101 BBB
20240201 DDD
20240301 CCC
20240401 DDD
20240501 BBB

Solution

  • Do have a look at the DAX Time intelligence functions.

    Here is an example of what your measures could look like:

    // base measure
    # Merchant =
      CALCULATE(
        DISTINCTCOUNTNOBLANK(DimMerchant[MerchantHK]),
        FactTransaction
      )
    
    // Last Month or Previous Month
    # Merchant LM = CALCULATE([# Merchant], PREVIOUSMONTH(DimDate[DateValue]))
    
    // Last 3 months (not including current selected month)
    # Merchant L3M =
      CALCULATE(
        [# Merchant],
        DATESINPERIOD(DimDate[DateValue], MAX(DimDate[DateValue]) - 1, -3, MONTH)
      )
    
    // Last 12 months (not including current selected month)
    # Merchant LY =
      CALCULATE(
        [# Merchant],
        DATESINPERIOD(DimDate[DateValue], MAX(DimDate[DateValue]) - 1, -12, MONTH)
      )