2010-10-14 96 views
1

我正在運行下面的查詢,需要在底部包括一個總計,但不知道如何在SQL SERVER中運行它。 (我可以複製數據並在Excel中進行自動求和,但它有點重複性)請問有人能幫忙嗎?總結SQL Server或ORACLE中的聚合

SELECT 
LOCATION, 
SUM(CASE WHEN my_date >= '10/1/2009' AND my_date <'01/01/2010' THEN QTY 
    ELSE NULL END) AS QTR1, 

SUM(CASE WHEN my_date >= '01/1/2010' AND my_date <'04/01/2010' THEN QTY 
    ELSE NULL END) AS QTR2, 

SUM(CASE WHEN my_date >= '04/1/2010' AND my_date <'07/01/2010' THEN QTY 
    ELSE NULL END) AS QTR3, 

SUM(CASE WHEN my_date >= '07/1/2010' AND my_date <'10/01/2010' THEN QTY 
    ELSE NULL END) AS QTR4 
FROM MYTABLE 
GROUP BY location 



Location QTR1 QTR2 QTR3 QTR4 
FL 171  174  99  177 
MD 662  640  422  497 
VA 2,713 4,454 3,062 2,793 
NY 479  380  227  477 
PA 7,197 10,078  5,625 6,448 
NJ 2,626 3,848 2,428 2,089 
TOTAL ??? ??? ??? ??? 
+1

如果您發佈的代碼或XML,** **請在高亮文本編輯器的線路,然後點擊編輯器工具欄上的「代碼」按鈕(101 010)至很好的格式和語法突出顯示它! – 2010-10-14 14:33:39

回答

1

是否GROUP BY LOCATION WITH ROLLUP你需要什麼?

;WITH MYTABLE AS 
(
SELECT 'FL' AS LOCATION,CAST('10/1/2009' AS DATETIME) AS my_date, 1 AS QTY UNION ALL 
SELECT 'MD' AS LOCATION,'10/1/2009' AS my_date, 27 AS QTY UNION ALL 
SELECT 'MD' AS LOCATION,'01/1/2010' AS my_date, 1024 AS QTY UNION ALL 
SELECT 'FL' AS LOCATION,'07/1/2010' AS my_date, 98 AS QTY UNION ALL 
SELECT 'FL' AS LOCATION,'07/1/2010' AS my_date, 5 AS QTY 
) 
SELECT 
COALESCE(LOCATION,'TOTAL'), 
SUM(CASE WHEN my_date >= '10/1/2009' AND my_date <'01/01/2010' THEN QTY 
    ELSE NULL END) AS QTR1, 
SUM(CASE WHEN my_date >= '01/1/2010' AND my_date <'04/01/2010' THEN QTY 
    ELSE NULL END) AS QTR2, 
SUM(CASE WHEN my_date >= '04/1/2010' AND my_date <'07/01/2010' THEN QTY 
    ELSE NULL END) AS QTR3, 
SUM(CASE WHEN my_date >= '07/1/2010' AND my_date <'10/01/2010' THEN QTY 
    ELSE NULL END) AS QTR4 
FROM MYTABLE 
GROUP BY LOCATION WITH ROLLUP 

返回

 QTR1  QTR2  QTR3  QTR4 
----- ----------- ----------- ----------- ----------- 
FL 1   NULL  NULL  103 
MD 27   1024  NULL  NULL 
TOTAL 28   1024  NULL  103 
0

我認爲這應該工作的變種。僅僅通過位置刪除分組,並使用此查詢:

SELECT SUM(CASE WHEN my_date >= '10/1/2009' AND my_date <'01/01/2010' THEN QTY ELSE NULL END) AS QTR1, 

SUM(CASE WHEN my_date >= '01/1/2010' AND my_date <'04/01/2010' THEN QTY ELSE NULL END) AS QTR2, 

SUM(CASE WHEN my_date >= '04/1/2010' AND my_date <'07/01/2010' THEN QTY ELSE NULL END) AS QTR3, 

SUM(CASE WHEN my_date >= '07/1/2010' AND my_date <'10/01/2010' THEN QTY ELSE NULL END) AS QTR4 FROM MYTABLE