Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
3 years ago
Solved

How can I convert a table with duplicate IDs and string values in Power Query?

First, I need to duplicate each row when ID = ABC. Then, I need to divide each row into three and change the ID from ABC to 021, 026, 111, as these are the only IDs with strings. Do you have any ideas for how to accomplish this using Power Query?

Region HoursFruitIDDate
Austria 12appleABC12.12.2022
Austria 10pineapple ABC12.12.2023

How do I convert from this table to this one? 

Region HoursFruitIDDate
Austria 4apple02112.12.2022
Austria 4apple02612.12.2022
Austria 4apple11112.12.2022
China3.33pineapple 02112.12.2023
China3.33pineapple 02612.12.2023
China3.33pineapple 11112.12.2023

 

  • Hi Anonymous ,

     

    Try this:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WciwtLinKTFRQ0lEyNAISiQUFOalA2tHJGSykB0RGBkZGSrE6qIoNgERBZl4qWIMCpg5jZB0gCVMgkZSYB4RAhourG5riWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Region " = _t, Hours = _t, Fruit = _t, ID = _t, Date = _t]),
        chgTypes = Table.TransformColumnTypes(Source,{{"Region ", type text}, {"Hours", Int64.Type}, {"Fruit", type text}, {"ID", type text}, {"Date", type date}}),
    
    //Relevant steps from here ------->
        addNewID = Table.AddColumn(chgTypes, "newID", each if [ID] = "ABC" then {"021", "026", "111"} else {[ID]}),
        addNewHours = Table.AddColumn(addNewID, "newHours", each [Hours] / List.Count([newID])),
        expandNewID = Table.ExpandListColumn(addNewHours, "newID")
    in
        expandNewID

     

    To get this output:

     

    I've assumed that you want to keep the existing [ID] if it's not "ABC".

     

    Pete

1 Reply

  • Hi Anonymous ,

     

    Try this:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WciwtLinKTFRQ0lEyNAISiQUFOalA2tHJGSykB0RGBkZGSrE6qIoNgERBZl4qWIMCpg5jZB0gCVMgkZSYB4RAhourG5riWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Region " = _t, Hours = _t, Fruit = _t, ID = _t, Date = _t]),
        chgTypes = Table.TransformColumnTypes(Source,{{"Region ", type text}, {"Hours", Int64.Type}, {"Fruit", type text}, {"ID", type text}, {"Date", type date}}),
    
    //Relevant steps from here ------->
        addNewID = Table.AddColumn(chgTypes, "newID", each if [ID] = "ABC" then {"021", "026", "111"} else {[ID]}),
        addNewHours = Table.AddColumn(addNewID, "newHours", each [Hours] / List.Count([newID])),
        expandNewID = Table.ExpandListColumn(addNewHours, "newID")
    in
        expandNewID

     

    To get this output:

     

    I've assumed that you want to keep the existing [ID] if it's not "ABC".

     

    Pete