我试图在多个列上进行透视。我正在使用SQL Server2008。这是到目前为止我尝试过的
CREATE TABLE #t ( id int, Rscd varchar(10),Accd varchar(10),position int)
INSERT INTO #t Values (10,'A','B',1)
INSERT INTO #t Values (10,'C','D',2)
Select id,[1],[2],[11],[12] FROM
(SELECT id, Rscd,Accd, position , position +10 as Aposition
From #t)
As query
PIVOT (MAX(Rscd )
FOR Position IN ([1],[2])) AS Pivot1
PIVOT (MAX(Accd )
FOR Aposition IN ([11],[12])) AS Pivot2
以下是我得到的结果
id 1 2 11 12
10 NULL C NULL D
10 A NULL B NULL
但是我想要达到的结果是,
id 1 2 11 12
10 A C B D
有什么帮助吗?我的代码有什么问题。
我将先将各列成对旋转,然后再将它们旋转。基本上,逆透视过程中会转化列对(rscd
,position
和accd
,aposition
)为行,那么你可以申请支点。该代码将是:
select id, [1], [2], [11], [12]
from
(
select id, col, value
from #t
cross apply
(
select rscd, position union all
select Accd, position + 10
) c (value, col)
) d
pivot
(
max(value)
for col in ([1], [2], [11], [12])
) piv;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句