這種類型的數據轉換可以在SQL Server應用兩個UNPIVOT
,然後PIVOT
函數來完成。
的UNPIVOT
功能需要你列Alias
,ShortName
,LongName
和IssuerID
並將它們轉換到行值。然而,爲了使UNPIVOT
工作這些值的數據類型必須相同:
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
見SQL Fiddle with Demo
一旦數據已經UNPIVOT
版,那麼你可以申請的PIVOT
功能的Typename
列值:
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
見SQL Fiddle with Demo
查詢的結果是:
| 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 |
如果您沒有訪問UNPIVOT
和PIVOT
功能,那麼你可以使用一個UNION ALL
查詢複製UNPIVOT
,然後用CASE
集合函數來複制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
見SQL Fiddle with Demo
結果將是這兩個版本是相同的。
你試過了什麼?你會想要將數據轉移。快速的Google搜索會使您朝正確的方向發展。 –
select * from Table1 pivot(avg(IssuerID)for TypeName in([Fields],[Current],[Provisional],[Legacy]))TypeName這不起作用!... –
@AdamWenger小心示範的列名稱成爲價值的PIVOT? –