SQL Pivot / unpivot列名和相应的值

时间:2016-11-02 19:52:15

标签: sql pivot

我目前有一个返回一行数据的查询。我想将最后的4或5分成一列,旁边有相应的值。

See sample image

2 个答案:

答案 0 :(得分:0)

USE UNION

        SELECT peojectID,level_type,'LABOR' as Cost_Type,LABOR as Cost From Table UNION
        SELECT peojectID,level_type,'TRAVEL' as Cost_Type,TRAVEL as Cost From Table UNION
        SELECT peojectID,level_type,'MATERIAL' as Cost_Type,MATERIAL as Cost From Table UNION 
        SELECT peojectID,level_type,'ODCs' as Cost_Type,ODCs as Cost From Table UNION 
        SELECT peojectID,level_type,'FEE' as Cost_Type,FEE as Cost From Table 
        OEDER BY peojectID,level_type

答案 1 :(得分:0)

如果您使用的是MSSQL,那么试试这个

   SELECT peojectID,level_type, Cost_type,Cost  
    FROM   
       (SELECT peojectID,level_type, LABOR, TRAVEL, MATERIAL, ODCs, FEE 
       FROM Table) p  
    UNPIVOT  
       (Cost  FOR Cost_type IN   
          (LABOR, TRAVEL, MATERIAL, ODCs, FEE )  
    )AS unpvt;