Search code examples
sqlsql-serverunpivot

columns to rows maintaining userid


I have columns that look like this:

UserID    col1    col2    col3    col4
---------------------------------------
233432    45.2    34.2    ''      0.52

I want it to look like this:

UserID    colID    value
-------------------------
233432    col1     45.2
233432    col2     34.2
233432    col3     ''
233432    col4     0.52

I found this link below:

column to row in sql server?

but it doesn't really answer the question I have.my question. I am using Sql Server 2012.


Solution

  • Select UserID,'col1',col1 as 'value' from mytable
    union
    Select UserID,'col2',col2 from mytable
    union
    Select UserID,'col3',col3 from mytable
    union
    Select UserID,'col4',col4 from mytable