有几种不同的方法可以获得您想要的结果。如同@Sheela K R's https://stackoverflow.com/a/21250732/426671答案您可以使用带有 CASE 表达式的聚合函数,但它可以以更简洁的方式编写:
select
max(case when rowid = 1 then first end) First1,
max(case when rowid = 1 then last end) Last1,
max(case when rowid = 2 then first end) First2,
max(case when rowid = 2 then last end) Last2,
max(case when rowid = 3 then first end) First3,
max(case when rowid = 3 then last end) Last3,
max(case when rowid = 4 then first end) First4,
max(case when rowid = 4 then last end) Last4,
max(case when rowid = 5 then first end) First5,
max(case when rowid = 5 then last end) Last5
from yourtable;
See SQL 摆弄演示 http://sqlfiddle.com/#!3/026ec/2.
这也可以使用 PIVOT 函数编写,但是由于您想要旋转多个列,那么您首先需要查看取消旋转First
and Last
列。
逆透视过程会将多列转换为多行数据。您没有指定您正在使用的 SQL Server 版本,但您可以使用SELECT
with UNION ALL
with CROSS APPLY
甚至是UNPIVOT
执行第一次转换的函数:
select col = col + cast(rowid as varchar(10)), value
from yourtable
cross apply
(
select 'First', First union all
select 'Last', Last
) c (col, value)
See SQL 摆弄演示 http://sqlfiddle.com/#!3/026ec/3。这会将您的数据转换为以下格式:
| COL | VALUE |
|--------|-------------|
| First1 | RandomName1 |
| Last1 | RandomLast1 |
| First2 | RandomName2 |
| Last2 | RandomLast2 |
一旦数据位于多行中,您就可以轻松应用 PIVOT 函数:
select First1, Last1,
First2, Last2,
First3, Last3,
First4, Last4,
First5, Last5
from
(
select col = col + cast(rowid as varchar(10)), value
from yourtable
cross apply
(
select 'First', First union all
select 'Last', Last
) c (col, value)
) d
pivot
(
max(value)
for col in (First1, Last1, First2, Last2,
First3, Last3, First4, Last4, First5, Last5)
) piv;
See SQL 摆弄演示 http://sqlfiddle.com/#!3/026ec/4
两者给出的结果是:
| FIRST1 | LAST1 | FIRST2 | LAST2 | FIRST3 | LAST3 | FIRST4 | LAST4 | FIRST5 | LAST5 |
|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|
| RandomName1 | RandomLast1 | RandomName2 | RandomLast2 | RandomName3 | RandomLast3 | RandomName4 | RandomLast4 | RandomName5 | RandomLast5 |