SQL SUM不是SUM特定列

时间:2013-09-28 02:59:26

标签: sql oracle

如何使用数据库oracle在我的表中汇总我的列(Q.QTY)? 像这样的SQL代码:

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';

当我在TOAD中查询此SQL代码时,它将在Q.QTY列中显示所有数据,而不显示所有数据。

我想要的是这样的:

QTY
5000 (example value)

请指教。感谢

2 个答案:

答案 0 :(得分: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

请注意,您有不明确的列名和未命名的列,所以我不得不给它们一个别名。

答案 1 :(得分: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';