Google-sheets – Transposing varied number of columns per entry into duplicate entries with one column in Google Sheets

google sheets

I feel almost certain this has been answered, but in a time crunch I am hoping someone can outline the solution for me, as my searches returned variations that were not quite what I wanted.

I have data that is arranged with multiple columns per entry:

unique number with multiple columns of data

I would like to transpose the columns data into rows duplicating the first two columns as indices:

multiple rows per unique number with each columns data transposed.

Much appreciation for any solutions.

Best Answer

As you have noted, there is a precedent for this on either StackOverflow or webapps but I couldn't find it, so I've recreated an equivalent solution. I'm pretty sure that this formula can be simplified BUT it does work - so simplification is for another day/user.

Use this formula (assumes that the raw data is in sheet="Data"):

=query({{"Number","Name","Code"};sort(query({query({query({query({query(Data!A2:B6) ,query(Data!A2:F6) },"select Col1, Col2, Col5 where Col1 = Col3");query({query(Data!A2:B6) ,query(Data!A2:F6) },"select Col1, Col2, Col6 where Col1 = Col3 and Col6 is not null")});query({query(Data!A2:B6) ,query(Data!A2:F6) },"select Col1, Col2, Col7 where Col1 = Col3 and Col7 is not null")});query({query(Data!A2:B6) ,query(Data!A2:F6) },"select Col1, Col2, Col8 where Col1 = Col3 and Col8 is not null")}),2,true)})

The logic is

  • create four(4) x two-array queries: the first part is Columns A & B (Col1 and Col2), the second part is Columns A to F (Col3 to Col8)
    • each query lists Col1 and Col2 and one of Col5 to Col 8 respectively.
    • these quesries are then stacked. Note that are joined between curly brackets and separated by a semicolon {;}
  • the end result is then sorted using SORT
  • the last step is to add the column headings (though this is optional) by creating another two-array query

BEFORE

Before

AFTER

After