Forum Discussion

fturmo's avatar
fturmo
Frequent Visitor
9 years ago
Solved

Power BI Desktop: Variables in Measures

Dear all,   I am trying to create a measure that calculates the differences in hours between two columns taking into account the weekends and non worked days.   I am using the follwoing formula f...
  • v-ljerr-msft's avatar
    9 years ago

    Hi fturmo,

    The result of that formula is OK for each individual member but i don't know how to calculate the aggregate (average) for all the rows in the table.

    In this scenario, you may need two measures to work this out. First measure to calculate the time difference for the individual column which is similar to the measure you provided above.. The formula below is for your reference.

    Measure Time For Individual Member =
    VAR startdate =
        MAX ( Table1[Start Date] )
    VAR enddate =
        MAX ( Table1[End Date] )
    VAR Firstdayend =
        DATE ( YEAR ( startdate ), MONTH ( startdate ), DAY ( startdate ) + 1 )
    VAR LastdayStart =
        DATE ( YEAR ( enddate ), MONTH ( enddate ), DAY ( enddate ) )
    VAR LastdayEnd =
        DATE ( YEAR ( enddate ), MONTH ( enddate ), DAY ( enddate ) + 1 )
    VAR secondsfirstday =
        IF ( Firstdayend <= startdate, 0, DATEDIFF ( startdate, Firstdayend, SECOND ) )
    VAR secondslastday =
        IF (
            enddate >= LastdayStart
                && enddate <= LastdayEnd,
            DATEDIFF ( LastdayStart, enddate, SECOND ),
            IF ( enddate > LastdayEnd, DATEDIFF ( LastdayStart, LastdayEnd, SECOND ), 0 )
        )
    VAR secondsmidday =
        (
            CALCULATE (
                DISTINCTCOUNT ( 'Calendar'[Date Calculations] ),
                FILTER (
                    'Calendar',
                    'Calendar'[Date Calculations] > startdate
                        && 'Calendar'[Date Calculations] < enddate
                        && 'Calendar'[Is Weekday] = TRUE ()
                )
            )
                - 1
        )
            * 3600
            * 24
    RETURN
        ( secondsfirstday + secondslastday
            + secondsmidday )
            / 3600

    Then use a new measure to sum each individual time difference together for the table.

    Measure Avg Time = SUMX ( Table1, [Measure Time For Individual Member] )

    Regards