尝试了很多SQL小提琴,但无处可去。我在表格中有以下内容
Col1 | Col2 | Col3
-------------------
A | B | C
D | E | F
G | H | I
我需要输出
A | D | G
B | E | H
C | F | I
请有人帮忙。我知道PIVOT可能是最好的选择吗?
由于
答案 0 :(得分:3)
首先将其取消,然后将其推回去。
with --Build up as we go
--Start with original data
t (Col1, Col2, Col3)
as
( select 'A','B','C'
union all select 'D','E','F'
union all select 'G','H','I')
,
--Put rownums in there - they'll help
numbered as (
select row_number() over (order by Col1) as rownum, *
from t)
,
--Now unpivot the data, using cross apply.
unpivotted as (
select r.rownum, c.colnum, c.val
from numbered r
cross apply (values (1, Col1), (2, Col2), (3, Col3)) as c (colnum, val)
)
--Now pivot it back again, grouping by colnum
select max(case when rownum = 1 then val end),
max(case when rownum = 2 then val end),
max(case when rownum = 3 then val end)
from unpivotted
group by colnum;