ROLLUP,CUBE或GROUPING SETS

时间:2013-08-23 14:21:12

标签: sql sql-server sql-server-2008-r2 cube rollup

有关架构详细信息,请参阅http://sqlfiddle.com/#!3/1b16f/7的链接。我使用动态数据透视查询来获取月份详细信息。现在,我试图获得“transactional”和“Customer”的子总数以及最终在同一个数据透视查询中的总计。到目前为止,我已尝试使用立方体和汇总进行分组,但未获得满意的结果。

我试图在最后实现这一目标。

+---------------------+---------------+-------------+-------------+-------------+
|         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。请帮忙!!

1 个答案:

答案 0 :(得分: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小提琴进行演示:http://sqlfiddle.com/#!3/1b16f/18