问题
I am trying to allocate inventory items to open orders in DAX, PowerBi. The idea is to allocate all the available inventory to the oldest order first, then allocate the remaining inventory to the second oldest, etc. until the inventory is depleted. The inventory can be depleted even if the open order is not completely satisfied.
Please check the attached picture as an example for the allocations below
I tried adding a column in the open order table using the Calculate function but the results were not correct at all. It didn't do any allocations, it just summed up the inventory.
CALCULATE (
[QOH],
FILTER (
ALL ( 'Open Orders'[Parent Name] ),
'Open Orders'[Due Date] <= MAX ( ( 'Open Orders'[Due Date] ) )
)
)
回答1:
The tricky part here is calculating what was ordered before the date on the current row but you can do that by looking at the sum for previous due dates.
This should work as a calculated column:
Inventory Allocation =
VAR TotalInventory =
LOOKUPVALUE ( Inventory[Qty On Hand], Inventory[Item], 'Open Orders'[Item] )
VAR AlreadyOrdered =
CALCULATE (
SUM ( 'Open Orders'[Qty Open] ),
ALL ( 'Open Orders' ),
Inventory[Item] = EARLIER ( 'Open Orders'[Item] ),
'Open Orders'[Due Date] < EARLIER ( 'Open Orders'[Due Date] )
)
RETURN
IF (
AlreadyOrdered > TotalInventory,
0,
MIN ( 'Open Orders'[Qty Open], TotalInventory - AlreadyOrdered )
)
Edit:
In the AlreadyOrdered
definition, the ALL
argument says to remove all the row/filter context from the table and the following arguments specify the filtering I do want and is equivalent to the REMOVEFILTERS funcion inside of a CALCULATE
.
The EARLIER function is often confusing to people as it has nothing to do with dates but refers to the earlier row context so I can refer to the value in the current row of the table while writing a condition inside a CALCULATE
. You could use variables instead:
Inventory Allocation =
VAR TotalInventory =
LOOKUPVALUE ( Inventory[Qty On Hand], Inventory[Item], 'Open Orders'[Item] )
VAR CurrItem = 'Open Orders'[Item]
VAR CurrDate = 'Open Orders'[Due Date]
VAR AlreadyOrdered =
CALCULATE (
SUM ( 'Open Orders'[Qty Open] ),
REMOVEFILTERS ( 'Open Orders' ),
Inventory[Item] = CurrItem,
'Open Orders'[Due Date] < CurrDate
)
RETURN
IF (
AlreadyOrdered > TotalInventory,
0,
MIN ( 'Open Orders'[Qty Open], TotalInventory - AlreadyOrdered )
)
来源:https://stackoverflow.com/questions/61063251/dax-allocate-inventory-to-open-orders