我有一个select语句,它返回一个最多包含四个结果的列结果表
Result
aaa
bbb
ccc
ddd
我需要一个新表格,如下所示
aaa bbb ccc ddd
在让很多人建议使用Pivot之前看一下,但似乎我需要知道初始选择语句的结果,在这种情况下我不会这样做。
有没有这样做?
答案 0 :(得分:2)
如果总共有4行,你可以使用row_number为你生成4列你知道的(数字1..4),如下所示:
select * from (
select row_number () over (order by (select null)) RN, *
from (
select 'aaa' as Result
union all
select 'bbb'
union all
select 'ccc'
union all
select 'ddd'
) X
) S
pivot (max(Result) for RN in ([1],[2],[3],[4])
) P
结果:
1 2 3 4
aaa bbb ccc ddd
中的示例
答案 1 :(得分:0)
你可以做类似的事情 -
select max(case when rn = 1 then result end) as col1,
max(case when rn = 2 then result end) as col2,
max(case when rn = 3 then result end) as col3,
max(case when rn = 4 then result end) as col4
from
(select result,row_number() over (order by (select 1)) as rn
from TableA
) as A