2013-09-28 156 views
0

如何使用數據庫oracle在我的表中填充我的列(Q.QTY)? 的SQL代碼:SQL SUM not SUM特定列

SELECT DISTINCT 
M.MODEL_NO, 
P.FORM_NO, 
P.MODEL_NO, 
TO_CHAR(TO_DATE(P.DATE_ADDED,'YYYY-MM-DD'),'MONTH'), 
Q.FORM_NO, 
Q.STATUS_QTY, 
SUM(Q.QTY) OVER (PARTITION BY P.FORM_NO ORDER BY P.FORM_NO 
RANGE UNBOUNDED PRECEDING) QTY 

FROM 
SEIAPPS_MODEL M, SEIAPPS_PRODUCTION_STATUS P, SEIAPPS_QTY Q 

WHERE 
P.FORM_NO = Q.FORM_NO AND P.MODEL_NO = M.MODEL_NO AND M.MODEL_NO = '15' AND P.DATE_ADDED LIKE '2013-05%' AND Q.STATUS_QTY = 'OK'; 

當我查詢蟾蜍這個SQL代碼,它會顯示所有數據,而不是總和所有Q.QTY列。

我想要的東西是這樣的:

QTY 
5000 (example value) 

請指點。由於

回答

0

最簡單的就是用你的查詢作爲派生表並添加所有列的總和:

SELECT SUM(MODEL_NO1) + SUM(FORM_NO1) + SUM(MODEL_NO2) + SUM(TOCHAR) + 
    SUM(FORM_NO2) + SUM(STATUS_QTY) + SUM(QTY) AS SUM_ALL 
FROM 
(
    SELECT DISTINCT 
    M.MODEL_NO AS MODEL_NO1, 
    P.FORM_NO AS FORM_NO1, 
    P.MODEL_NO AS MODEL_NO2, 
    TO_CHAR(TO_DATE(P.DATE_ADDED,'YYYY-MM-DD'),'MONTH') AS TOCHAR, 
    Q.FORM_NO AS FORM_NO2, 
    Q.STATUS_QTY, 
    SUM(Q.QTY) OVER (PARTITION BY P.FORM_NO ORDER BY P.FORM_NO 
    RANGE UNBOUNDED PRECEDING) QTY 

    FROM 
    SEIAPPS_MODEL M, SEIAPPS_PRODUCTION_STATUS P, SEIAPPS_QTY Q 

    WHERE 
    P.FORM_NO = Q.FORM_NO AND P.MODEL_NO = M.MODEL_NO AND M.MODEL_NO = '15' AND P.DATE_ADDED LIKE '2013-05%' AND Q.STATUS_QTY = 'OK' 
) x 

說明你有不明確的列名和未命名的列,所以我不得不給他們的別名。

+0

如何繼續在我的代碼?實際上對於SUM_ALL只是例子...我需要SUM SUM(Q.QTY)中的所有列..謝謝 –

+0

@AseanJazz對不起,我不關注 –

+0

沒關係,所以有什麼建議? –

0

我看起來像你想Q.QTY全部的總數。您正在使用窗口功能。更多信息在這裏。

http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm#i81407

另外,我建議使用ANSI連接語法來代替。

SELECT DISTINCT 
M.MODEL_NO, 
P.FORM_NO, 
P.MODEL_NO, 
TO_CHAR(TO_DATE(P.DATE_ADDED,'YYYY-MM-DD'),'MONTH'), 
Q.FORM_NO, 
Q.STATUS_QTY, 
SUM(Q.QTY) OVER (PARTITION BY P.FORM_NO ORDER BY P.FORM_NO 
RANGE UNBOUNDED PRECEDING) QTY 
SUM(Q.QTY) OVER() As SumOfAll -- Sum of the entire QTY column 
FROM SEIAPPS_MODEL M 
JOIN SEIAPPS_PRODUCTION_STATUS P 
    ON P.MODEL_NO = M.MODEL_NO 
JOIN SEIAPPS_QTY Q 
    ON P.FORM_NO = Q.FORM_NO 
WHERE 
    M.MODEL_NO = '15' AND P.DATE_ADDED LIKE '2013-05%' AND Q.STATUS_QTY = 'OK';