Power BI Dax 用复杂的逻辑计算时间间隔

Power BI Dax Calculate Time Intervals With Complicated Logic

我想计算这个table中每个任务的滞后时间。延迟计算一个任务完成下一个任务开始之间的时间间隔。

有案例(CaseNum),一个案例可以有不同的任务(TaskNum),一个阶段( TaskStage)代表一个任务的当前阶段(但不需要连续,我们可以跳到下一个阶段).

rank 是我创建的参考列,用于显示每个案例下的任务阶段顺序。

Lag的逻辑比较复杂---

table 中的背景颜色表示我用来计算延迟的日期对。希望它可以帮助理解逻辑。谢谢!!!

假设您尝试计算计算列,您可以尝试以下操作:

Lag = 
-- getting a table with lagged rows (ranks smaller then current rows rank)
VAR lags =
    FILTER (
        ALL ( 'Table' ),
        'Table'[CaseNum]
            -- EARLIER() will get the 'outer' row context's CaseNum
            -- outer row context: calculated column one
            = EARLIER ( 'Table'[CaseNum] )
            && 'Table'[rank]
                < EARLIER ( 'Table'[rank] )
    )

-- extracting only the direct previous rank
VAR lag_value =
    MAXX (
        lags,
        'Table'[rank]
    )

-- checking if there is a previous task (rank value is not blank)
VAR cond =
    ISBLANK ( lag_value )

-- getting currents row InitDate (in calculated columns row context)
VAR current_date = 'Table'[InitDate]

-- getting the date from the previous task 
VAR last_date =
    CALCULATE (
        MAX ( 'Table'[CompletedDate] ),
        FILTER (
            ALL ( 'Table' ),
            'Table'[CaseNum]
                = EARLIER ( 'Table'[CaseNum] )
                && 'Table'[rank] = lag_value
        )
    )
RETURN
    IF (
        cond,
        -- if blank, return the days between approval and init
        DATEDIFF (
            'Table'[ApproveDate],
            'Table'[InitDate],
            DAY
        ),
        -- else return days between last completed and init, 
        -- negative values will be set to 0
        MAX (
            DATEDIFF (
                last_date,
                current_date,
                DAY
            ),
            0
        )
    )