Power BI DAX : Get sum of a column based on another

馋奶兔 提交于 2021-02-05 06:48:46

问题


Let say I have the folowwing table :

Client    Sales
A         1000
A         100
A         10
B         1000
B         10
C         1

I would like to add another column Names TotalClient at the end which would the new table look like this :

Client    Sales   Total
A         1000    1110
A         100     1110
A         10      1110
B         1000    1010
B         10      1010
C         1       1

Is this possible either in DAX or in the query editor ? I tried many ways, but still can't figure out how.

I was able to get information I needed using the SUMMARIZE function to get another table, but I run into other problem in term of security. It seems the data table gets filtered right, but not the summarized version.

Thanks


回答1:


You just need to know how to use CALCULATE to adjust your filter context.

Total = CALCULATE( SUM( Table1[Sales] ), ALLEXCEPT( Table1, Table1[Client] ) )

This says to calculate the sum of the sales for all rows in the table where we've removed any row context except for the client. Thus you get the sum over all rows where the client matches the client in the current row.


If you only have these columns, you can do this

Total = CALCULATE( SUM( Table1[Sales] ), ALL( Table1[Sales] ) )

This removes only the Sales row context and leaves the Client row context. This probably will not work as expected if you have other columns as well since they will still be part of the row context.


You can also remove all filter context with ALL and then explicitly add back in the filtering you want:

Total =
CALCULATE(
    SUM( Table1[Sales] ),
    ALL( Table1 ),
    Table1[Client] = EARLIER( Table1[Client] )
)

or do similarly with SUMX instead

Total =
SUMX(
    FILTER(
        Table1,
        Table1[Client] = EARLIER( Table1[Client] )
    ),
    Table1[Sales]
)

Lots of ways to skin the cat.



来源:https://stackoverflow.com/questions/53192212/power-bi-dax-get-sum-of-a-column-based-on-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!