-2

Table:

CompanyID   Lead   LeadManager
------------------------------
    1          2         3

Required output:

CompanyID   Role          RoleID
--------------------------------
   1        Lead            2
   1        Leadmanager     3
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Jeswanth
  • 177
  • 2
  • 5
  • 14
  • Does this answer your question? [Unpivot with column name](https://stackoverflow.com/q/19055902/2029983) – Larnu Jan 13 '20 at 12:19

2 Answers2

0

You can use union all to unpivot your dataset. This is a standard solution that works across most (if not all) RDBMS:

select companyID, 'Lead' role, Lead from mytable
union all select companyID, 'LeadManager', LeadManager from mytable
GMB
  • 195,563
  • 23
  • 62
  • 110
0

You can use apply to unpivot the data:

select v.*
from t cross apply
     (values (t.CompanyId, 'Lead', t.Lead),
             (t.CompanyId, 'LeadManager', t.LeadManager)
     ) v(CompanyId, Role, RoleId);

The advantage to this approach is that it scans the original table only once. This can be particular helpful when the "table" is a complex query.

Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709