Forum Discussion

criztina14's avatar
criztina14
Frequent Visitor
1 year ago
Solved

Distinct count on dynamic query using unrelated dimension tables

I was asked to compare the number of distinct clients in the current year vs lifetime. We're still discussing if this is really needed but I'm not sure if this would be actually possible to get.   ...
  • darkniqht's avatar
    1 year ago

    You can easily get the distinct count of customers for the current year using a measure like this:

     

    DistinctCustomersCurrentYear =
    DISTINCTCOUNT(MainTable[CustomerID])

     

    For the lifetime distinct count, since you’re dealing with unrelated dimension tables, you can use a combination of DAX and context. Try creating a measure that calculates the distinct count while ignoring the slicers for the lifetime table:

     

    DistinctCustomersLifetime =
    CALCULATE(
        DISTINCTCOUNT(LifetimeTable[CustomerID]),
        ALL(MainTable)  // Ignores current year filters
    )

     

    To filter the lifetime data based on slicers, you can create a measure that checks for the selected products or stores from the slicers and then uses that context to filter the lifetime data:

     

    DistinctCustomersLifetimeFiltered =
    CALCULATE(
        DISTINCTCOUNT(LifetimeTable[CustomerID]),
        FILTER(
            LifetimeTable,
            LifetimeTable[StateID] IN VALUES(MainTable[StateID]) // Adjust as necessary
        )
    )

     

    If you’re using DirectQuery, you may be limited in how you pass slicer values. You might need to look into using stored procedures or creating a SQL view that combines these tables dynamically.

     

    Finally, create visuals that show both measures side by side for comparison. This will help illustrate the differences between the distinct customer counts.