Forum Discussion

ShamR9T's avatar
ShamR9T
Frequent Visitor
2 years ago
Solved

Change Cumulative Sums back to differences

I have a data source in the following form   Sales Person Location Item 1-Jan-23 8-Jan-23 15-Jan-23 22-Jan-23 A 1 Z 1 1 2 2 B 2 X 0 0 1 2 C 3 Y 0 1 2 3 A 3 ...
  • rubayatyasmin's avatar
    2 years ago

    Hi, ShamR9T 

     

    there was some miss calculations in the previous solution. 

     

    the solution is okay now. 

     

    There is some workaround in this query that you need to modify. 

     

    Here is the PQ code

     

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCk7MSS1WCEgtKs7PU9JR8slPTizJBDM9S1JzgZShrldinq6RMZBpgWAamiLYRkYwdqxOtJIjSBaIo6A0CBuBMUjWCcqLAGIDKDaEyzoDWSATI1FkQGIwk42hekEypkBsDsbIJkcimQzBMJNhrkKTjQUA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"(blank)" = _t, #"(blank).1" = _t, #"(blank).2" = _t, #"(blank).3" = _t, #"(blank).4" = _t, #"(blank).5" = _t, #"(blank).6" = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"(blank)", type text}, {"(blank).1", type text}, {"(blank).2", type text}, {"(blank).3", type text}, {"(blank).4", type text}, {"(blank).5", type text}, {"(blank).6", type text}}),
        #"Promoted Headers" = Table.PromoteHeaders(#"Changed Type", [PromoteAllScalars=true]),
        #"Changed Type1" = Table.TransformColumnTypes(#"Promoted Headers",{{"Sales Person", type text}, {"Location", Int64.Type}, {"Item", type text}, {"1-Jan-23", Int64.Type}, {"8-Jan-23", Int64.Type}, {"15-Jan-23", Int64.Type}, {"22-Jan-23", Int64.Type}}),
       // Step 2: Unpivot the date columns
        UnpivotedColumns = Table.UnpivotOtherColumns(#"Changed Type1", {"Sales Person", "Location", "Item"}, "Date", "Value"),
    
       // Step 3: Group by Sales Person, Location, Item, and Date
        GroupedTable = Table.Group(UnpivotedColumns, {"Sales Person", "Location", "Item", "Date"}, {{"Cumulative Sum", each List.Max([Value]), type number}}),
        AddIndex = Table.AddIndexColumn(GroupedTable, "Index", 0, 1, Int64.Type),
    
         AddPreviousDaySales = Table.AddColumn(AddIndex, "Previous Day Sales", each if [Index] > 0 then AddIndex{[Index]-1}[Cumulative Sum] else 0),
        AddSalesEachDay = Table.AddColumn(AddPreviousDaySales, "Sales Each Day", each [Cumulative Sum] - [Previous Day Sales]),
        
        // Step 4: Remove unnecessary columns
        RemovedColumns = Table.RemoveColumns(AddSalesEachDay,{"Index", "Previous Day Sales"})
    in
        RemovedColumns

     

    try to understand the values that is showing minus, the calculation is alright with the given logic. You wan to subtract values with the previous values. You need to adjust it a little bit. But this should be very helpful.