Search code examples
powerbipattern-matchinggroupingpowerquery

Power Query -- Group-by-Result Expand


Here's an example of my existing data set. I have unique parts (Part) grouped by what factory # (Factory) they're used in and when the parts started to be used in operation (Part Install Year).

Part Factory Part Install Year
1 100 2018
2 100 2018
3 100 2018
3 200 2019
3 300 2020
4 400 2019
5 400 2020
6 500 2018

Desired Output is below. I need to group all the related parts by the lowest numbered factory they are installed in (Part Grouping) and then calculate the earliest year any part was installed in that factory (Factory Install Year). I'm having trouble figuring out how to create the Factory Install Year. Thank you!

Part Factory Part Install Year Part Grouping Factory Install Year
1 100 2018 100 min of all Dates in Factory 100
2 100 2018 100 min of all Dates in Factory 100
3 100 2018 100 min of all Dates in Factory 100
3 200 2019 100 min of all Dates in Factory 100
3 300 2020 100 min of all Dates in Factory 100
4 400 2019 400 min of all Dates in Factory 400
5 400 2020 400 min of all Dates in Factory 400
6 500 2018 500 2018

Solution

  • Try

    let  Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Part Install Year", type number}, {"Factory", type number}}),
    EarliestYear = Table.Group(#"Changed Type", {"Factory"}, {{"EarliestYear", each List.Min([Part Install Year]), type nullable number}}),
    #"Grouped Rows" = Table.Group(  #"Changed Type", {"Part"}, {
        {"data", each _, type table },
        {"MinFactory", each List.Min([Factory])},
        {"EarliestYear", each try EarliestYear[EarliestYear]{List.PositionOf(EarliestYear[Factory],List.Min([Factory]))} otherwise null}
    }),
    #"Expanded data" = Table.ExpandTableColumn(#"Grouped Rows", "data", {"Factory", "Part Install Year"}, {"Factory", "Part Install Year"})
    in #"Expanded data"
    

    enter image description here