Search code examples
sql-serverms-access-2010excel-2010powerqueryunpivot

Unpivot table with two rows as column headers


I know how to unpivot an Excel table with one row as column header using power query. But recently I had a need to unpivot with 2 rows as column header. For example if we have this:

    b1  b1  b2  b2  b2
    c1  c2  c1  c2  c3
a1   1   4   7   3   4
a2   5   8   9   8   6
a3   3   6   9   6   2

a=row heading and b & c=column headings

and we want this:

a1  b1  c1  1
a1  b1  c2  4
a1  b2  c1  7
a1  b2  c2  3
a1  b2  c3  4
a2  b1  c1  5
a2  b1  c2  8
a2  b2  c1  9
a2  b2  c2  8
a2  b2  c3  6
a3  b1  c1  3
etc.            

Solution

  • In Power Query, you can do this by

    1. Transposing the table and promoting headers to get:
    _   _1  a1  a2  a3
    b1  c1  1   5   3
    b1  c2  4   8   6
    b2  c1  7   9   9
    b2  c2  3   8   6
    b2  c3  4   6   2
    
    1. Then you can unpivot the a columns.
        _1  Atr Value
    b1  c1  a1  1
    b1  c1  a2  5
    b1  c1  a3  3
    b1  c2  a1  4
    b1  c2  a2  8
    b1  c2  a3  6
    b2  c1  a1  7
    b2  c1  a2  9
    b2  c1  a3  9
    b2  c2  a1  3
    b2  c2  a2  8
    b2  c2  a3  6
    b2  c3  a1  4
    b2  c3  a2  6
    b2  c3  a3  2
    
    1. Rearrange, sort, and rename columns as desired.