我在SQL sever 2008中有一个像这样的表
ID Name Have
1 Book PageNumber
2 Book Title
3 Book Papers
4 Car Wheels
5 Car Doors
6 Car Engine
7 Car Windows
我想像这样改变列和行的顺序
Name A B C D
Book PageNumber Title Papers -
Car Wheels Doors Engine Windows
是否可以编写自动进行此更改的查询? 我在使用交叉表的Microsoft Access中完成了这个,但在SQL中我不知道。
的问候,
答案 0 :(得分:0)
您可以使用PIVOT运算符
来获得所需的结果select name
, [1] as A
, [2] as B
, [3] as C
, [4] as D
from ( select name
, have
, row_number() over(partition by name order by id) as rn
from t1
) s
pivot (
max(have) for rn in ([1], [2],[3], [4])
) as pvt
结果:
NAME A B C D
------------------------------------------------------------
Book PageNumber Title Papers (null)
Car Wheels Doors Engine Windows