SQL Server基于单列透视多个列

时间:2014-12-29 04:37:18

标签: sql-server sql-server-2008 sql-server-2008-r2 pivot

我的SQL Server 2008中有以下表格。

SourceTbl

ID | Name | Type  | Quantity1 | Quantity2
=========================================
1  | A    | Type1 | 3         | 3
2  | B    | Type2 | 4         | 0
3  | C    | Type3 | 2         | 1
1  | A    | Type2 | 5         | 2
1  | A    | Type1 | 2         | 1
3  | C    | Type1 | 6         | 6

DestTbl

Type1Quantity1= SUM(Quantity1)

Type2Quantity1= SUM(Quantity1)

Type3Quantity1= SUM(Quantity1)

Type1Quantity= SUM(Quantity1-Quantity2)

Type2Quantity= SUM(Quantity1-Quantity2)

Type3Quantity= SUM(Quantity1-Quantity2)

ID | Name | Type1Quantity1 | Type2Quantity1 | Type3Quantity1 | Type1Quantity | Type2Quantity | Type3Quantity
===========================================================================================================
1  | A    | 5              | 5              | NULL           | 1             | 3             | NULL
2  | B    | NULL           | 4              | NULL           | NULL          | 1             | NULL
3  | C    | 6              | NULL           | 2              | 0             | NULL          | 1 

我可以轻松地将其转移到以下列之一:PIVOT (SUM(Quantity1) FOR Type IN ([Type1],[Type2],[Type3]))

有人能给我一点帮助吗?感谢。

2 个答案:

答案 0 :(得分:0)

试试这个,

    SELECT Max(ID) AS ID,Name,Sum([Type1Quantity1]) AS [Type1Quantity1],Sum([Type2Quantity1]) AS [Type2Quantity1],Sum([Type3Quantity1]) AS [Type3Quantity1],
                          Sum([Type1Quantity])AS [Type1Quantity],Sum([Type2Quantity]) AS [Type2Quantity],Sum([Type3Quantity]) AS [Type3Quantity]
    FROM (SELECT ID , Name , TYPE+'Quantity1' AS TYPE , QUANTITY1 , QUANTITY2 ,QUANTITY1-QUANTITY2 AS Q1_Q2, TYPE+'Quantity' AS TYPE_T FROM #TEMP) A
    PIVOT (Sum(Quantity1) FOR TYPE IN ([Type1Quantity1],[Type2Quantity1],[Type3Quantity1])) PV
    PIVOT (SUM(Q1_Q2) FOR TYPE_T IN ([Type1Quantity],[Type2Quantity],[Type3Quantity])) PV1
    GROUP BY NAME

答案 1 :(得分:-1)

这是样本表

SELECT * INTO TEMPTABLE
FROM
(
    SELECT 1 ID  , 'A' Name  , 'Type1' [Type], 3 Quantity1         , 3 Quantity2
    UNION ALL
    SELECT 2  , 'B'    , 'Type2' , 4         , 0
    UNION ALL
    SELECT 3  , 'C'    , 'Type3' , 2         , 1
    UNION ALL
    SELECT 1  , 'A'    , 'Type2' , 5         , 2
    UNION ALL
    SELECT 1  , 'A'    , 'Type1' , 2         , 1
    UNION ALL
    SELECT 3  , 'C'    , 'Type1' , 6         , 6
)TAB

虽然在这种情况下您不需要dynamic Unpivot,但如果您需要在某个时候使用unpivot,则可以将其保留为dynamically

DECLARE @cols nvarchar(max) 
SELECT @cols = coalesce(@cols+N',', N'') + quotename(c.name) 
FROM syscolumns c
INNER JOIN sysobjects o on c.id = o.id and o.xtype = 'u'
WHERE o.name = 'TEMPTABLE' 
AND c.name NOT IN ('ID', 'Name','Type') 
ORDER BY c.colid

现在unpivot Quantity1,Quantity2,3,4.....

DECLARE @query nvarchar(max)  

SELECT @query = N'
SELECT ID, Name, [Type], Val,QNT
INTO UNPIVOTTABLE
FROM 
(
    SELECT ID, Name, [Type],'+ @cols + '
    FROM TEMPTABLE    
)AS TAB
unpivot
(
    Val for QNT in (' + @cols + ')
) AS UNP
'
EXEC sp_executesql @query

我在查询中编写了逻辑。将此查询发送到temporary table

;WITH CTE1 AS
(
    SELECT TAB.*,SUM(VAL) OVER(PARTITION BY TAB.NAME,PIVOTCOL) [TOTAL],TAB2.Q1-TAB2.Q2 DIFF
    FROM
    (   
        -- We combine the column names fpr displaying in pivoted result
        SELECT ID, Name,[Type],QNT,[Type]+QNT PIVOTCOL,VAL 
        FROM UNPIVOTTABLE
    )TAB
    JOIN
    (
        -- We take the sum of Quantity1 and Quanity2 
        SELECT DISTINCT ID, Name,[Type],
        SUM(Quantity1) OVER(PARTITION BY NAME,[TYPE]) Q1,
        SUM(Quantity2) OVER(PARTITION BY NAME,[TYPE]) Q2
        FROM TEMPTABLE
    )TAB2
    ON TAB.ID=TAB2.ID AND TAB.[Type]=TAB2.[TYPE]
)
-- Type1Quantity1,Type1Quantity2,Type2Quantity1 etc
SELECT DISTINCT 1 RNO,Name,PIVOTCOL,[TOTAL] INTO #NEWTABLE
FROM CTE1
UNION ALL
-- Type1Quantity,Type2Quantity,Type3Quantity
SELECT DISTINCT 2, Name,[Type]+'Quantity' ,DIFF 
FROM CTE1

获取枢轴列。在这里,我们根据Type1Quantity1,Type1Quantity2,Type2Quantity1......然后按Type1Quantity,Type2Quantity,Type3Quantity

订购列
DECLARE @PIVOTcols NVARCHAR (MAX)

SELECT @PIVOTcols = COALESCE (@PIVOTcols + ',[' + PIVOTCOL + ']', 
               '[' + PIVOTCOL + ']')
               FROM    (SELECT DISTINCT RNO,PIVOTCOL FROM #NEWTABLE) PV  
               ORDER BY RNO,PIVOTCOL

由于可能有n种类型,您可能需要pivot dynamically。请注意,我已将Quantity2字段也包含在透视结果中。

DECLARE @PIVOTquery NVARCHAR(MAX)
SET @PIVOTquery = '           
              SELECT * FROM 
             (
                 SELECT Name,PIVOTCOL,[TOTAL] FROM #NEWTABLE
             ) x
             PIVOT 
             (
                 SUM([TOTAL])
                 FOR [PIVOTCOL] IN (' + @PIVOTcols + ')
            ) p      

            '     
EXEC SP_EXECUTESQL @PIVOTquery

<强> RESULT

enter image description here