简体   繁体   中英

Power BI DAX with filter

I'm new to Power BI and DAX. I have a table that looks something like the one below在此处输入图像描述

I want to create a DAX measure to put on a card visualization; when I filter the page for a user name, it should display the AVERAGE of the value by department. For eg in this case if I filter by User 1 (department = Legal), I should get the average of three values for user 1 and two values for User 3 which in this case would be (0.255836 + 0.209221 + 0.326591 + 0.212668 + 0.191183)/5 = 0.2391

I tried using CALCULATE(AVERAGE(mytablename[value]), REMOVEFILTERS(tablename[username])) but this doesn't seem to work. How should I go about this?

One way to do this is this one:

AverageDpt = 
    var Cat = FIRSTNONBLANK(mytablename[Department],True)
return
    CALCULATE(AVERAGE(mytablename[Value]),filter(ALL(mytablename),mytablename[Department]=Cat))   

Explanation

  1. With the variable Cat you get the name of the department.
  2. In the Calculate function:
    2.1 All(mytablename) : removes all filters
    2.2 mytablename[Department]=Cat) : filters only those rows with the right department

Alternative
If, in case you need it to show the normal average if no user has been selected, you can use this code:

AverageDpt = 
    var Cat = FIRSTNONBLANK(mytablename[Department],True)
    var DistCount = DISTINCTCOUNT(mytablename[Department])
return
    if (DistCount=1,
        CALCULATE(AVERAGE(mytablename[Value]),filter(ALL(mytablename),mytablename[Department]=Cat)),
        AVERAGE(mytablename[Value]))

This is the result I get:
在此处输入图像描述

You're nearly there. Simply remove all filters, and re-apply the selected department filter context::

Departmental Average Value = 
    CALCULATE ( 
        AVERAGE ( MyTable[Value] ),
        REMOVEFILTERS (MyTable),
        MyTable[Department] = SELECTEDVALUE ( MyTable[Department] )
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM