Forum Discussion

jmontes1810's avatar
jmontes1810
Frequent Visitor
4 years ago
Solved

How to count each time some rows sum x number?

Hi community, This time, I need some help from you to count or assign a count each time some rows sum X quantity. For example, in the next table I would like to know how to get the column "Pallet L...
  • ronrsnfld's avatar
    ronrsnfld
    4 years ago

    You can create a "conditional" running total using List.Generate; then use List.Accumulate to develop the Pallet List.

     

    Data

     

     

     

    let
        Source = Excel.CurrentWorkbook(){[Name="Table7"]}[Content],
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"DN", type text}, {"QTY", Int64.Type}}),
    
    //generate list of pallets
    //replace >=80 with nulls to satisfy that condition
        qty= List.Buffer(List.Transform(#"Changed Type"[QTY], each if _ >=80 then null else _)),
    
    //Generate a running total of the qtys that start over when there is a null 
    // (ie an entry that was >=80) or when the running total reaches a Max of 80
        qtyList = List.Generate(
            ()=>[qt= qty{0}, idx=0],
            each [idx] < List.Count(qty),
            each [qt= if qty{[idx]+1} = null then null 
                        else if [qt] = null then  qty{[idx]+1} 
                        else if [qt] + qty{[idx]+1} <=80 then [qt] + qty{[idx]+1}
                        else qty{[idx]+1},
                    idx = [idx]+1],
            each [qt]),
    
    //generate the Pallet list by incrementing the list whenever the qty entry = the entry in the qtyList
    //Note that the seed has to be {0} as {} or {null} + any number => null
    //So we make the seed a {0} and remove that first entry when done generating the list.
        palletList = List.RemoveFirstN(
        List.Accumulate({0..List.Count(qty)-1},{0},(state,current)=>
            if qtyList{current} = null then state & {null} 
                else if qtyList{current} = qty{current} then state & {List.Max(state)+1} 
                else state & {List.Max(state)}
        ),1),
    
    //add to table
        tbl = Table.FromColumns( 
        Table.ToColumns(#"Changed Type") & {palletList},
        Table.ColumnNames(#"Changed Type") & {"Pallet List"})
    
    in  
        tbl

     

     

     

    Results