0

有关架构详细信息,请参阅http://sqlfiddle.com/#!3/1b16f/7的链接。我使用动态数据透视查询来获取月度详细信息。现在,我试图在同一个数据透视查询中获取“事务”和“客户”的小计以及最后的总计。到目前为止,我已经尝试使用多维数据集和汇总进行分组,但没有得到令人满意的结果。

我正在努力最终实现这一目标。

+---------------------+---------------+-------------+-------------+-------------+
|         CTQ         |     TYPE      |   Oct-12    |   Nov-12    |   Dec-12    |
+---------------------+---------------+-------------+-------------+-------------+
| CAR                 | CUSTOMER      | 4.019040077 | 4.128151178 | 4.05606883  |
| REJECTION           | CUSTOMER      | NULL        | NULL        | 3.126549759 |
| REOPEN              | CUSTOMER      | 3.010499668 | 3.043744049 | 2.985404802 |
| REPEAT              | CUSTOMER      | 3.086827141 | 3.055288995 | 3.202606293 |
| CUSTOMER TOTAL      |               | 2.111       | 2.111       | 2.111       |
| QMC                 | TRANSACTIONAL | 3.699047224 | 3.417352407 | 3.525099552 |
| SQ                  | TRANSACTIONAL | NULL        | 5.017541394 | 4.90992542  |
| TAT                 | TRANSACTIONAL | 2.548737677 | 2.509322914 | 2.538090124 |
| TTU                 | TRANSACTIONAL | 3.364436242 | 3.295240684 | 3.294951974 |
| TRANSACTIONAL TOTAL |               | 2.33        | 2.33        | 2.33        |
| GRAND TOTAL         |               | 2.12        | 2.12        | 2.12        |
+---------------------+---------------+-------------+-------------+-------------+

我正在使用 SQL Server 2008R2。请帮忙!!

4

1 回答 1

0

我能够用这个查询回答我的问题:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

  SELECT @cols = ISNULL(@cols+',','') + QUOTENAME(DATENAME(MONTH, MNTH)+' '+DATENAME(YEAR, MNTH)) 
    FROM CAPABILITY
   WHERE  MNTH BETWEEN DATEADD(M,-10,CURRENT_TIMESTAMP) AND DATEADD(M,0,CURRENT_TIMESTAMP)
    GROUP BY DATENAME(MONTH, MNTH), DATENAME(YEAR, MNTH), DATEPART(MONTH,mnth)
    ORDER BY DATENAME(YEAR, MNTH), DATEPART(MONTH,mnth)
SET @query = 'SELECT  TYPE,CTQ,' 

+@cols+ 
'FROM  

(
SELECT 
CASE 
WHEN CTQ IS NULL AND TYPE IS NULL THEN ''CUST + TRANS TOTAL''
WHEN CTQ IS NULL AND TYPE IS NOT NULL THEN TYPE+''TOTAL'' 
WHEN CTQ IS NULL AND TYPE IS NULL THEN ''''
WHEN GROUPING(TYPE)=1 THEN ''CUST + TRANS''
ELSE TYPE
END AS [TYPE],
CTQ,        
    SUM(opportunity)AS Sigma    

    ,DATENAME(MONTH, MNTH)+'' ''+DATENAME(YEAR, MNTH)
 AS MONTHS
    FROM CAPABILITY

        GROUP BY ROLLUP(CTQ), ROLLUP(TYPE),DATENAME(MONTH, MNTH)+'' ''+DATENAME(YEAR, MNTH)

)X

PIVOT 
            (
                MIN(SIGMA)
                FOR MONTHS in (' + @cols + ')
            ) X 

        ORDER BY TYPE ASC
           '
    --PRINT (@QUERY)
EXECUTE (@QUERY)

请参阅此 SQL Fiddle 进行演示:http ://sqlfiddle.com/#!3/1b16f/18

于 2013-08-23T17:17:23.377 回答