如何透视表以将行值反映为列?

时间:2013-04-16 07:21:14

标签: sql-server row pivot

SQL从查询中返回以下表格:

Application  FDate        Type   Value
-----------  ------      ----   ------
abcd         04/15/2013  CIndex  3.00
abcd         04/15/2013  CC     200000
abcd         04/15/2013  MI     400
xyz          04/15/2013  CIndex  2.50    
xyz          04/15/2013  CC     15000    
xyz          04/15/2013  MI     1200

我试图通过枢轴获得以下结果:

 Application  FDate        CIndex   CC     MI
-----------  ------       ----   ----   -----
 abcd         04/15/2013  3.00   200000  400
 xyz          04/15/2013  2.50   15000   1200

到目前为止的查询:

SELECT * FROM
(
  SELECT A.App_Name AS [Application],
  O.Functional_Date As FDate,
  CASE WHEN (T.TYPE_NAME LIKE 'Calculate Index') THEN 'CIndex'
  CASE WHEN (T.TYPE_NAME LIKE 'C Complexity') THEN 'CC'
  CASE WHEN (T.TYPE_NAME LIKE 'Medium Index') THEN 'MI' END TYPE,

CASE WHEN (T.TYPE_NAME LIKE 'Calculate Index') THEN ROUND (V.TypeValue, 2)
ELSE V.TypeValue END Value

FROM [DBServer1].[DB_A].[dbo].TypeTab AS T, [DBServer1].[DB_A].[dbo].AppName AS A,    [DBServer1].[DB_A].[dbo].DateTab AS O, [DBServer1].[DB_A].[dbo].ValueTab AS V 

WHERE T.Type_ID = V.Type_ID
      AND T.Type_index IN (0,1)... (several ANDs)
) src
PIVOT
( SUM (Type)
)piv

但这会引发错误。并且不确定即使我修复了错误,查询也会起作用。

请帮忙。

感谢您的期待!
阿希什

1 个答案:

答案 0 :(得分:1)

SELECT  [Application], 
        FDate,
        [Calculate Index] AS CIndex,
        [Cyc Complexity] AS CC,
        [Medium Index] AS MI
FROM    
        (
            SELECT  A.App_Name AS [Application],
                    O.Functional_Date As FDate,
                    T.TYPE_NAME,
                    ROUND (V.TypeValue, 2) Value
            FROM    [DBServer1].[DB_A].[dbo].TypeTab AS T, 
                    [DBServer1].[DB_A].[dbo].AppName AS A,    
                    [DBServer1].[DB_A].[dbo].DateTab AS O, 
                    [DBServer1].[DB_A].[dbo].ValueTab AS V 
            WHERE   T.Type_ID = V.Type_ID AND 
                    T.Type_index IN (0,1)... (several ANDs)
        ) org
        PIVOT
        (
            MAX(Value)
            FOR TYPE_NAME IN ([Index], [CC], [MI])
        ) pvt