0

如何使用数据库 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 列中所有的 SUM。

我想要的是这样的:

QTY
5000 (example value)

请指教。谢谢

4

2 回答 2

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

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

于 2013-09-28T03:03:30.843 回答
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';
于 2013-09-28T04:04:41.970 回答