How to calculate inventory per day from movement table with Power BI DAX?

隐身守侯 提交于 2019-12-01 20:59:05

This is a bit tricky, but we can do it with the use of a temporary calculated summary table within a measure:

CountStatusB =
    SUMX(
        ADDCOLUMNS(
            SUMMARIZE(
                FILTER(
                    ALL(Inventory),
                    Inventory[TimeStamp] <= MAX(Inventory[TimeStamp])
                ),
                Inventory[ID],
                "LastTimeStamp",
                MAX(Inventory[TimeStamp])
            ),
            "Status",
            LOOKUPVALUE(Inventory[Status],
                Inventory[ID], Inventory[ID],
                Inventory[TimeStamp], [LastTimeStamp])
            ),
        IF([Status] = "B",
            1,
            0
        )
    )

First, we create a summary table which calculates the last TimeStamp for each ID value. To do this, we use the SUMMARIZE function on a filtered table where we only consider dates from the current day or earlier, group by ID, and calculated the max TimeStamp.

Once we have the maximum TimeStamp per ID for the current day, we can look up what the Status is on that day and add that as a column to the summary table.

Once we know the most recent Status for each ID for the current day, we just need to sum up the ones where that Status is "B" and ignore the other ones.


It may be easier to read the measure if we break it up into steps. Here's the same logic as before, but using variables for more clarity.

CountB = 
    VAR CurrDay = MAX(Inventory[TimeStamp])
    VAR Summary = SUMMARIZE(
                      FILTER(
                          ALL(Inventory),
                          Inventory[TimeStamp] <= CurrDay
                      ),
                      Inventory[ID],
                      "LastTimeStamp",
                      MAX(Inventory[TimeStamp])
                  )
    VAR LookupStatus = ADDCOLUMNS(
                           Summary,
                           "Status",
                           LOOKUPVALUE(Inventory[Status],
                               Inventory[ID], Inventory[ID],
                               Inventory[TimeStamp], [LastTimeStamp]
                           )
                       )
    RETURN SUMX(LookupStatus, IF([Status] = "B", 1, 0))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!