我不确定你为什么认为你不能用 UNPIVOT
和 PIVOT
完成这个任务:
select [1], [2], [3], [4], [5]
from
(
select *
from
(
select col1, col2, col3,
row_number() over(order by col1) rn
from yourtable
) x
unpivot
(
val for col in (col1, col2, col3)
) u
) x1
pivot
(
max(val)
for rn in ([1], [2], [3], [4], [5])
) p
请查看带有演示的SQL Fiddle。如果需要,这也可以动态执行。
如果需要保留列的顺序,则可以使用类似以下代码的方式,在表中的某一列上应用row_number()
而不使用order by
(这里有一篇关于使用非确定性行号的文章):
select [1], [2], [3], [4], [5]
from
(
select *
from
(
select col1, col2, col3,
row_number()
over(order by (select 1)) rn
from yourtable
) x
unpivot
(
val for col in (col1, col2, col3)
) u
) x1
pivot
(
max(val)
for rn in ([1], [2], [3], [4], [5])
) p;
请查看带有演示的SQL Fiddle