Search code examples
sqlsql-serverunpivotlateral-join

How create a group variable from the two columns


I have the following table

enter image description here

How can I achieve the following table result:

enter image description here

group1 and group2 should be united in one column.


Solution

  • You can use cross apply to unpivot your dataset:

    select g.twogroups, t.year, t.quantity
    from mytable t
    cross apply (values (t.group1), (t.group2)) as g(twogroups)