Search code examples
sqlsql-servert-sqlunpivot

Convert column into the rows


This is my current result set of my query:

Question   Sol25A   Sol25B   Sol25C   Sol40A   Sol40B
======================================================
A           1        4          2       6         0
B           2        3          2       1         9
C           6        7          1       0         8
======================================================
Total =    9         14         5       7         17
======================================================

And I want the result in this form:

Product   Total
===============
Sol25A      9
Sol25B      14
Sol25C      5
Sol40A      7
Sol40B      17

Can you please provide me the query for me, this will be the great help for me.


Solution

  • I would suggest that you unpivot using cross apply and then aggregate:

    select product, sum(val)
    from t cross apply
         (values ('Sol25A', Sol25A), ('Sol25B', Sol25B), ('Sol25C', Sol25C),
                 ('Sol40A', Sol40A), ('Sol40B', Sol40B)
         ) v(product, val)
    group by product;