Reputation: 107
I have a table like below in power BI with two columns Category and subcategory. I m trying to get the count of subcategory="S2" for each category into a calculated column (like in S2_count).
Category Subcategory S2_count
A S1 1
A S2 1
A S1 1
B S1 2
B S3 2
B S2 2
B S2 2
C S2 2
C S3 2
C S2 2
Is there a way using the DAX to get this ? I tried the below formula but no clue how to apply both filter and group by
s2_count =
CALCULATE(
COUNT(Test01[subcategory]),
GROUPBY(Test01,Test01[subcategory]))
Upvotes: 3
Views: 18057
Reputation: 40254
You can also do this using CALCULATE
.
s2_count =
CALCULATE( COUNTROWS( Test01 ),
Test01[Subcategory] = "S2",
ALLEXCEPT( Test01, Test01[Category] )
)
The ALLEXCEPT
function removes any of the row context except for the Category
.
Note: If there are no other columns in your table, you don't need the ALLEXCEPT
argument and you can just use this instead:
s2_count = CALCULATE( COUNTROWS( Test01 ), Test01[Subcategory] = "S2" )
If you do have other columns though, they are passed from row context to filter context along with the Category
and you won't get the right result.
Upvotes: 1
Reputation: 2967
Thy this:
s2_count =
COUNTROWS (
FILTER (
'Test01',
'Test01'[Category] = EARLIER ( 'Test01'[Category] )
&& 'Test01'[Subcategory] = "S2"
)
)
The EARLIER Function will return 'Test01'[Category] in its previous filtercontext, which is the rowcontext.
Upvotes: 1