行到列,反之亦然

时间:2013-07-03 07:08:15

标签: sql-server-2008

通过运行以下查询,我将得到以下结果。我想将这个结果转换成行,而不管那些我想要转换成列的那些行。

我希望project_level和account_level成行,其余的行转到列。

SELECT S.Description,T.Project_Level,S.Account_Level FROM
(           
   SELECT DISTINCT SM.Description, COUNT(VA.FK_Status_ID) AS Project_Level,SM.Seq
                  From DeliveryPlatform_APPS.VA.DP_VA_Item_Status_Master SM
                  LEFT OUTER JOIN DeliveryPlatform_APPS.VA.DP_VA_Items VA ON SM.Status_ID = VA.FK_Status_ID 
                  AND VA.FK_DP_Entity_Type_ID = 1 AND FK_DP_Entities=671
                  GROUP BY SM.Description,SM.Seq,FK_Status_ID           
) AS T            
INNER JOIN        
(           
  SELECT DISTINCT SM.Description, COUNT(VA.FK_Status_ID) AS Account_Level,SM.Seq
                  From DeliveryPlatform_APPS.VA.DP_VA_Item_Status_Master SM
                  LEFT OUTER JOIN DeliveryPlatform_APPS.VA.DP_VA_Items VA ON SM.Status_ID = VA.FK_Status_ID 
                  AND VA.FK_DP_Entity_Type_ID = 1 AND FK_DP_Entities=671
                  GROUP BY SM.Description,SM.Seq,FK_Status_ID           
) AS S 
ON S.Description=T.Description 
--ORDER BY Seq 

 Description      Project_Level      Account_Level

 Accepted          0                 0
 Closed            0                 0
 Delivered         0                 0
 Dropped           0                 0
 Open              0                 0
 Parked            0                 0
 Shortlisted       0                 0
 Work In Progress  0                 0

1 个答案:

答案 0 :(得分:1)

您应该检查SQL Server PIVOT和UNPIVOT技术以实现您的意图:

http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx