This type of data transformation can be done by applying both the UNPIVOT
and then the PIVOT
functions in SQL Server.
The UNPIVOT
function takes your columns Alias
, ShortName
, LongName
and IssuerID
and converts them to row values. However, in order for the UNPIVOT
to work the datatypes for these values must be the same:
select typename, value, fields
from
(
select cast(alias as varchar(20)) alias,
shortname,
longname,
cast(issuerid as varchar(20)) issuerid,
typename
from Table1
) u
unpivot
(
value
for fields in (Alias, ShortName, LongName, IssuerId)
) unpiv
See SQL Fiddle with Demo
Once the data has been UNPIVOT
ed, then you can apply the PIVOT
function to the Typename
column values:
select fields, [current], [provisional], [legacy]
from
(
select typename, value, fields
from
(
select cast(alias as varchar(20)) alias,
shortname,
longname,
cast(issuerid as varchar(20)) issuerid,
typename
from Table1
) u
unpivot
(
value
for fields in (Alias, ShortName, LongName, IssuerId)
) unpiv
) src
pivot
(
max(value)
for typename in([current], [provisional], [legacy])
) piv
See SQL Fiddle with Demo
The result of the query is:
| FIELDS | CURRENT | PROVISIONAL | LEGACY |
----------------------------------------------------------
| alias | 1 | 2 | 3 |
| issuerid | 23 | 34 | 50 |
| longname | ABC Pvt Ltd. | DEF Pvt Ltd. | GHI Pvt Ltd. |
| shortname | ABC | DEF | GHI |
If you do not have access to the UNPIVOT
and PIVOT
functions, then you can use a UNION ALL
query to replicate the UNPIVOT
and then an aggregate function with a CASE
to replicate a PIVOT
:
select fields,
max(case when typename = 'current' then value end) [current],
max(case when typename = 'provisional' then value end) provisional,
max(case when typename = 'legacy' then value end) legacy
from
(
select typename, cast(alias as varchar(20)) value, 'alias' fields
from Table1
union all
select typename, shortname value, 'shortname' fields
from Table1
union all
select typename, longname value, 'longname' fields
from Table1
union all
select typename, cast(issuerid as varchar(20)) value, 'issuerid' fields
from Table1
) src
group by fields
See SQL Fiddle with Demo
The result will be the same with both versions.