Forum Discussion

Antoinette123's avatar
1 year ago
Solved

Power Query: after combining 2 tables got something strange

I have a column "Name", in which each value is repeated twice. And each value has its own share (input data). I need to calculate the average share among the first occurrence of values in the first column, and the average for the second occurrence, for each subgroup (the subgroups are distinguished by the first part of the name: like input car 1, car 1, car 2, car 2, bike 1, bike 1, bike 2, bike 2, etc (word + number). An example is shown in the figure. I already created an occurrence index.

   
OwnerNameShareIndexwhat I need ->OwnerNameShareIndexAverage share
BobCar 10,451 BobCar 10,451(0,45+0,4)/2
BobCar 10,552 BobCar 10,552(0,55+0,6)/2
BobCar 20,41 BobCar 20,41(0,45+0,4)/2
BobCar 20,62 BobCar 20,62(0,55+0,6)/2
AlexBike 10,31 AlexBike 10,31(0,3+0,2)/2
AlexBike 10,72 AlexBike 10,72(0,7+0,8)/2
AlexBike 20,21 AlexBike 20,21(0,3+0,2)/2
AlexBike 20,82 AlexBike 20,82(0,7+0,8)/2

 To solve the task, I used "group by" and most of my columns disappeared in the new table. And when I try to merge the tables, I get strange results with many rows being repeated million times.

  • lbendlin's avatar
    lbendlin
    1 year ago
    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcspPUtJRck4sUjAE0gY6JqZAylApVgdTyhQkZYQmZQTRhUUTRMYMrscxJ7UCyHHKzE6FGmgM14UpZ45VH8RMI6z6IHIWEH2xAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Owner = _t, Name = _t, Share = _t, Index = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Share", type number}},"de"),
        #"Added Custom" = Table.AddColumn(#"Changed Type", "Average Share", (k)=> List.Average(Table.SelectRows(#"Changed Type", each [Owner]=k[Owner] and [Index]=k[Index])[Share]),type number)
    in
        #"Added Custom"

    How to use this code: Create a new Blank Query. Click on "Advanced Editor". Replace the code in the window with the code provided here. Click "Done". Once you examined the code, replace the Source step with your own source.

6 Replies