SQL: Real Transpose

隐身守侯 提交于 2019-11-27 14:52:00

I am unsure why you think you cannot accomplish this with an UNPIVOT and a 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

See SQL Fiddle with Demo. This could also be performed dynamically if needed.

Edit, if the column order needs to be kept, then you can use something like this, which applies the row_number() without using a order by on one of the columns in your table (here is an article about using non-deterministic row numbers):

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;

See SQL Fiddle with Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!