Forum Discussion

naveen73's avatar
naveen73
Helper III
2 years ago
Solved

Power Query columns depending on value

Hi all, I have a row of values. See below screenshot (I am not able to attach the Excel file 🤔). In each of the columns to the right I want the total of each value that is 70 at maximum if the who...
  • spinfuzer's avatar
    spinfuzer
    2 years ago

    Deleting old replies and pasting newest code here.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjNXitWJVjIxBVOmZmDKHEIZm4ApQyMIbWKOLGkG1BELAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Value = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Value", Int64.Type}}),
        dif_cols = Table.Combine(let
                limit1 = 120, // change upper limit 
                limit2 = 100, // chagne lower limit
                min = limit2, //List.Max({70,limit2}), old code for testing
                buffer = List.Buffer(#"Changed Type"[Value]), // Change to TableName[ColumnName]
                ct = List.Count(buffer)
            in 
                List.Generate( () =>
                [ 
                    n = 0, 
                    curr = {buffer{n}}, 
                    total = curr{0}, 
                    remainder = 0,
                    col = 1
                ], 
                each [n] < ct,
                each [ 
                    n = [n] + 1, 
                    curr = if [total] <= min then { buffer{n} } & [curr] else {buffer{n}} , 
                    total = List.Sum(curr) + [remainder],
                    remainder = if total >= limit1 then List.Max({total - limit2,0}) else if total >= min then 0 else [remainder],
                    col = if [total] <= min then [col] else [col] + 1
                ],
                each 
                    #table(
                        {//"test", 
                            "Col " & Text.From([col]),"Col " & Text.From([col]+1)}, // Change "Col " to change prefix
                            {
                                //{[total]} & 
                                (if [total] >= limit1 then {[curr]{0}-[remainder],[remainder]} else {[curr]{0},null})
                            }
                    )
                )),
        add_cols = Table.FromColumns(
            Table.ToColumns(#"Changed Type") & Table.ToColumns(dif_cols), 
            Table.ColumnNames(#"Changed Type") & Table.ColumnNames(dif_cols)
        ) // Change to #Changed Type to your prior table name
    in
        add_cols
  • naveen73's avatar
    naveen73
    2 years ago

    @spinfuzer

     

    Thanks so much for this solution. It does what I asked for. Much appreciated!!