Search code examples
powerbidaxpowerbi-desktopmeasure

Creating New Dynamic Column in a Power BI Table: Count values in another column and return different response based on the filter context


I am quite new to DAX and filter context so any help is appreciated.

I am looking to add another column to a table visual in Power BI based on a new measure. I need the measure to do the following:

  • Count the occurrences of a name in the column 'Name'.
  • If there is one count of a name in the table return 'Out' in the new column.
  • If there are two counts of a name in the table return 'In' in the new column.
  • I would like this to be dynamic, so that the value can change between 'In' and 'Out' depending on the filter context.

Example below showing how it should work:

Table1 (no filters) John shows as 'In' in the new column as his name appears twice.

Name Department New Column
John HR In
John Marketing In
Julie Marketing Out
Jake Sales Out

If you then filter Department to show just Marketing (using a slicer on the same page), I would like John to change to 'Out' as there is now only one occurrence of the name John.

Name Department New Column
John Marketing Out
Julie Marketing Out

I cannot get this dynamic nature to work!

I have created this measure, which does not change dynamically with the filters, all rows are listed with 'Out' no matter what filters are applied and how many counts of a name there are:

New Column =

VAR Name_Count = COUNTROWS(VALUES(Table1[Name]))

RETURN
IF(
Name_Count > 1,
"In",
"Out"
)


Solution

  • Try:

    New Column = 
      var thisName = SELECTEDVALUE(Table1[Name])
      var nameCount = COUNTROWS(FILTER(ALLSELECTED(Table1), [Name] = thisName))
      var result = IF(nameCount > 1, "In", "Out")
      return IF(ISINSCOPE('Table1'[Name]), result)
    

    The key is ALLSELECTED https://learn.microsoft.com/en-us/dax/allselected-function-dax