使用PIVOT SQL Server 2008时更改列名称

时间:2011-11-14 14:15:26

标签: sql-server-2008 pivot

    SELECT * FROM EmployeeAttributes
PIVOT (
     MAX(VALUE)
     FOR AttributeID IN ([DD14C4C2-FC9E-4A2E-9B96-C6A20A169B2E],[BE8149E2-0806-4D59-8482-58223C2F1735],[23B2C459-3D30-41CA-92AE-7F581F2535D4])
      ) P

结果

    EmployeeID                           DD14C4C2-FC9E-4A2E-9B96-C6A20A169B2E               BE8149E2-0806-4D59-8482-58223C2F1735               23B2C459-3D30-41CA-92AE-7F581F2535D4
------------------------------------ -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
329999EA-6288-4E7D-87E8-12FF865AB301 Rauf                                               23                                                 10
34E2B762-F065-42BB-B4D8-2252102F1C20 Amal                                               NULL 

                                          5

现在我如何在EmployeeID之后将列名更改为Name,Age,Salary?

2 个答案:

答案 0 :(得分:17)

使用AS提供列别名。

SELECT EmployeeID,
       [DD14C4C2-FC9E-4A2E-9B96-C6A20A169B2E] AS Name,
       [BE8149E2-0806-4D59-8482-58223C2F1735] AS Age,
       [23B2C459-3D30-41CA-92AE-7F581F2535D4] AS Salary
FROM   EmployeeAttributes PIVOT ( MAX(VALUE) FOR AttributeID IN (
       [DD14C4C2-FC9E-4A2E-9B96-C6A20A169B2E],
       [BE8149E2-0806-4D59-8482-58223C2F1735],
       [23B2C459-3D30-41CA-92AE-7F581F2535D4]) ) P  

答案 1 :(得分:10)

可能存在更简单的解决方案,但将PIVOT语句结果放入子查询允许您对外部选择中的列进行别名。

SELECT  EmployeeID = EmployeeID
        , Name = [DD14C4C2-FC9E-4A2E-9B96-C6A20A169B2E]
        , Age = [BE8149E2-0806-4D59-8482-58223C2F1735]
        , Salary = [23B2C459-3D30-41CA-92AE-7F581F2535D4]
FROM    (
          SELECT  * 
          FROM    EmployeeAttributes
          PIVOT   (MAX(VALUE) FOR AttributeID IN (
                  [DD14C4C2-FC9E-4A2E-9B96-C6A20A169B2E]
                  , [BE8149E2-0806-4D59-8482-58223C2F1735]
                  , [23B2C459-3D30-41CA-92AE-7F581F2535D4])
          ) P
        ) P