Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Be one of the first to start using Fabric Databases. View on-demand sessions with database experts and the Microsoft product team to learn just how easy it is to get started. Watch now

Reply
adnanarain
Helper V
Helper V

Cumulative Total reset when negative with measure

Need help with inventory dashboard i am using following data, total IN and total sales are measures and i want to calculate comulative ending inventory but the column should be reset when we have negative inventory and start over the commulative total.

using following measure but result is not correct issue with end inventory and beg inv for next month should be end inv of last month.

 

 

Cumulative Ending Inventory = 
VAR CurrentMonth = max(DateTable[Date]) -- Get the current month context
VAR PreviousMonths = 
    FILTER(
        ALL(DateTable),
        DateTable[Date] <= CurrentMonth
    )

-- Start with the first month's beginning inventory
VAR InitialInventory = [Beginning_Inventory_First_Month]

-- Calculate cumulative inventory change (Total IN + Sales) up to the current month
VAR CumulativeInventoryChange = 
   SUMX(
        PreviousMonths,
        [Total IN] + [Total Sales]
    ) --+ abs([CurrentInventoryChange_PreviousMonth_Dani])

-- Calculate the current month's ending inventory
VAR CurrentEndingInventory = 
    InitialInventory + CumulativeInventoryChange

-- Calculate the previous month's ending inventory
VAR PreviousEndingInventory = 
    CALCULATE(
        IF(
            (InitialInventory + 
            SUMX(
                FILTER(ALL(DateTable), DateTable[Date] < CurrentMonth),
                [Total IN] + [Total Sales]
            )) < 0,  -- If this condition is true (ending inventory is negative)
            [Total IN] + [Total Sales],  -- Use this value if the condition is true (reset to Total IN + Sales)
            InitialInventory + 
            SUMX(
                FILTER(ALL(DateTable), DateTable[Date] < CurrentMonth),
                [Total IN] + [Total Sales] 
            )  -- Use this value if the condition is false (carry forward previous inventory)
        ),
        PREVIOUSMONTH(DateTable[Date])  -- Apply this over the previous month
    )

RETURN 
    IF(
        PreviousEndingInventory < 0,
        MAX(0, [Total IN] + [Total Sales]),  -- Start from 0 with this month's IN and Sales
        MAX(0, CurrentEndingInventory)  -- Otherwise, continue with the cumulative calculation
    )

 

 

PeriodBeg InvTotal InTotal SalesEnd Inv (Current result)Expected OutputItem Name 
4/1/2023 0:00139416-9421300513005ATLANTIS 155 
5/1/2023 0:0013005180-31721001310013ATLANTIS 155 
6/1/2023 0:0010013108-153885838583ATLANTIS 155 
7/1/2023 0:0085830-116074237423ATLANTIS 155 
8/1/2023 0:0074230-288545384538ATLANTIS 155 
9/1/2023 0:004538900-78546534653ATLANTIS 155 
10/1/2023 0:0046530-69639573957ATLANTIS 155 
11/1/2023 0:0039571328-86944164416ATLANTIS 155 
12/1/2023 0:0044160-39640204020ATLANTIS 155 
1/1/2024 0:0040200-50435163516ATLANTIS 155 
2/1/2024 0:003516994-46840424042ATLANTIS 155 
3/1/2024 0:00404224-62834383438ATLANTIS 155 
4/1/2024 0:0034380-84225962596ATLANTIS 155 
5/1/2024 0:002596698-53227622762ATLANTIS 155 
6/1/2024 0:0027620-46023022302ATLANTIS 155 
7/1/2024 0:0023020-95013521352ATLANTIS 155 
8/1/2024 0:0013526-822536536ATLANTIS 155 
9/1/2024 0:005360-73100ATLANTIS 155where end inventory is less than 0 then 0 and start cumulative calculation again
10/1/2024 0:0002506-70917971797ATLANTIS 155 
11/1/2024 0:0016025900-95765456740ATLANTIS 155Column B21 should be 1797 (from last months End inventory)
12/1/2024 0:0065450-75157945989ATLANTIS 155Column B22 should be 6740 (from last months End inventory)
4/1/2023 0:003030700-6036703670DFR7 
5/1/2023 0:0036700-100026702670DFR7 
6/1/2023 0:0026700-72019501950DFR7 
7/1/2023 0:0019500019501950DFR7 
8/1/2023 0:0019500-50114491449DFR7 
9/1/2023 0:0014490-1000449449DFR7 
10/1/2023 0:0044900449449DFR7 
11/1/2023 0:004491300-50012491249DFR7 
12/1/2023 0:001249500-50012491249DFR7 
1/1/2024 0:001249700-50414451445DFR7 
2/1/2024 0:0014450-514401440DFR7 
3/1/2024 0:001440550-919811981DFR7 
4/1/2024 0:001981500-21522662266DFR7 
5/1/2024 0:002266600-45424122412DFR7 
6/1/2024 0:0024120-58818241824DFR7 
7/1/2024 0:0018240-73810861086DFR7 
8/1/2024 0:0010860-951135135DFR7 
9/1/2024 0:001350-61000DFR7 
10/1/2024 0:0001000-620380380DFR7 
11/1/2024 0:00380400-6600120DFR7 
12/1/2024 0:0000-61000DFR7 
4 REPLIES 4
v-zhengdxu-msft
Community Support
Community Support

Hi @adnanarain 

 

Please try this:

You can open the Advanced editor and paste these code in it:

vzhengdxumsft_1-1727070908706.png

 

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("fZVNagQhEIWvEmadgfrVchkIgUDIIpndkPtfI22p1cO09qJx8z2rtN6z7/cLAfEV5Ap4eb0gF6lr2r5rEdqWt9vX2/ft8/cFVS9/r0OgQwCgdTWoEsZ8okldA4Dsq1UNKttak5vG1KrEiyAmWAusCbJQCMhM14LSBNLaKOCSfKJA6IqkUSKVtOax8Vw0+5WRn9tSWUuolxBMowQvS9ThdR4IBq8ga77vz+r7l1LRq6TVIDYFjwruCnJBohNBtxSL36u3ZEtHSTiK1M+Zil+S8omi+4lyolFBltaQ8BIxBF/0hLfhcaWRCaOTfrqTlGNmmXGJDxuBHxp8+wwrT0jYaHN/7UG7U5upFpI+5qSi0ZKuWtqfAQaubG4V/ErfP37yMf6ccvhti/UEHDN6ADNNuD4bbAMZ3xNkB2hzOR65PggUKafdRZKDmzD4yNT3rpWdkP22kRzVFbnHtZMZHgL7RFIcJSaoR4qDqoRqc8aRG898Mdw7JJzsONJIydPYSNFJh2PCgpEqNTtyY8Lmb0ePx4QbQwaLGBV9HvKeti2d8Qjj8aofU9Y9sD1bE2480v4jkw4erL9nCmZV//4B", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Period = _t, #"Beg Inv" = _t, #"Total In" = _t, #"Total Sales" = _t, #"Item Name" = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Beg Inv", Int64.Type}, {"Total In", Int64.Type}, {"Total Sales", Int64.Type}, {"Period", type date}}),
    #"Grouped Rows" = Table.Group(#"Changed Type", {"Item Name"}, {{"Count", each Table.AddIndexColumn(_, "Index", 1, 1, Int64.Type)}}),
    #"Expanded Count" = Table.ExpandTableColumn(#"Grouped Rows", "Count", {"Period", "Beg Inv", "Total In", "Total Sales", "Index"}, {"Period", "Beg Inv", "Total In", "Total Sales", "Index"}),
    AddOutputColumn = Table.AddColumn(#"Expanded Count", "output", each List.Accumulate(
        Table.SelectRows(#"Expanded Count", (row) => row[Index] <= _[Index] and row[Item Name] = _[Item Name]) [Index],
        0,
        (state, current) =>
            let
                currentItem = Table.SelectRows(#"Expanded Count", (row) => row[Index] = current and row[Item Name] = _[Item Name]),
                currentValues = currentItem{0},
                previousOutput = if current = 1 then currentValues[Beg Inv] else state,
                newOutput = previousOutput + currentValues[Total In] + currentValues[Total Sales],
                finalOutput = if newOutput < 0 then 0 else newOutput
            in
                finalOutput
        ), type number)
in
    AddOutputColumn

It's worth noting that you only need to copy #"Grupedros" and the following  rows, the above does not need to be changed.

vzhengdxumsft_0-1727070553389.png

The result is as follow:

vzhengdxumsft_2-1727070947257.png

 

 

Best Regards

Zhengdong Xu
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

 

calculation take ages to complete when i implementated on real data as total sales and total in are also calculation based on the values from 2 different tables.

Please provide sample data that fully covers your issue.
Please show the expected outcome based on the sample data you provided.

lbendlin
Super User
Super User

Conditional accumulation is generally not supported in DAX.  For very small datasets you may be able to get away with identifying the last time inventory dipped, and start from there.  For all other scenarios your only option is Power Query's List.Accumulate which allows conditional accumulation.

 

You could also argue that when you sell more than you have inventory then you cannot just set that inventory to zero - a negative inventory correctly represents your backlog.

Helpful resources

Announcements
Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount!

Dec Fabric Community Survey

We want your feedback!

Your insights matter. That’s why we created a quick survey to learn about your experience finding answers to technical questions.

ArunFabCon

Microsoft Fabric Community Conference 2025

Arun Ulag shares exciting details about the Microsoft Fabric Conference 2025, which will be held in Las Vegas, NV.

December 2024

A Year in Review - December 2024

Find out what content was popular in the Fabric community during 2024.