1

我在 SQL 服务器 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 中我不知道。

问候,

4

1 回答 1

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

SQLFiddle 演示

于 2013-07-28T07:58:38.907 回答