Search code examples
powerbidax

Calculate a rate by category (DAX, PowerBI)


I'm using PowerBI. My table Population displays data as follows (numbers are not correct) :

Year Country       Granularity Population
2014 Albania       Urban       1.3m
2014 Albania       Total       5.6m
2015 Albania       Urban
2015 Albania       Total
2014 Aghanistan    Urban
etc.

I am trying to get a measure of the urban rate for each country and each year.

I tried this :

Pct_urban = 
VAR __Measure_1 =
CALCULATE (
    SELECTEDVALUE ('Population'[Population_cor]),
    'Population'[Granularity] = "Urban"
)
VAR __Measure_2 =
CALCULATE (
    SELECTEDVALUE ('Population'[Population_cor]),
    'Population'[Granularity] = "Total"
)
KEEPFILTERS(VALUES('Population'[Year])),
CALCULATE(DIVIDE(__Measure_1,__Measure_2)

My code is not working, could you offer any advice ?


Solution

  • You need to calculate the urban rate by summing the populations for urban and total granularities separately and then dividing them with the exclusion of any existing filter on the Granularity column :

    Pct_urban = 
    VAR UrbanPopulation = 
        CALCULATE (
            SUM('Population'[Population]), 
            'Population'[Granularity] = "Urban",
            REMOVEFILTERS('Population'[Granularity])
        )
    VAR TotalPopulation = 
        CALCULATE (
            SUM('Population'[Population]), 
            'Population'[Granularity] = "Total",
            REMOVEFILTERS('Population'[Granularity])
        )
    RETURN
        DIVIDE(UrbanPopulation, TotalPopulation)