-2

Table:

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

Required output:

CompanyID   Role          RoleID
--------------------------------
   1        Lead            2
   1        Leadmanager     3
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jeswanth
  • 187
  • 2
  • 6
  • 14
  • Does this answer your question? [Unpivot with column name](https://stackoverflow.com/q/19055902/2029983) – Thom A 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
  • 216,147
  • 25
  • 84
  • 135
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,242,037
  • 58
  • 646
  • 786