我正在尝试在多个列上进行转向。我正在使用SQL Server 2008.这是我到目前为止所尝试的
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
有任何帮助吗?我的代码有什么问题。
答案 0 :(得分:11)
我会首先将列拆分成对,然后转动它们。基本上,unpivot进程会将列对(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;
答案 1 :(得分:4)
Select id,sum([1]),sum([2]),sum([11]),sum([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
group by id
答案 2 :(得分:-3)
不要使用ID列。使用派生表检索除ID之外的所有列,然后使用PIVOT表。