我需要帮助找出如何从Oracle数据库中优化以下SQL查询:
SELECT DISTINCT
PR.DOC_ID, PR.AMEND_NO, LEDGER.ACCT_ID, APPRVL_CHAIN.APPRVR,
SUM(LEDGER.COMMIT)
FROM
LUFSMGR.APPRVL_CHAIN APPRVL_CHAIN,
LUFSMGR.LEDGER LEDGER,
LUFSMGR.PR PR
WHERE
PR.DOC_ID = LEDGER.DOC_ID
AND LEDGER.DOC_ID = APPRVL_CHAIN.DOC_ID
AND APPRVL_CHAIN.AMEND_NO = LEDGER.AMEND_NO
AND LEDGER.AMEND_NO = PR.AMEND_NO
AND ((PR.DOC_ID Like '2116%')
AND (LEDGER.ACCT_ID Like '25601 105300SD%')
AND (APPRVL_CHAIN.APPRVR_ROLE='Funds Manager'))
GROUP BY
PR.DOC_ID, PR.AMEND_NO, LEDGER.ACCT_ID, APPRVL_CHAIN.APPRVR
HAVING
(SUM(LEDGER.COMMIT) <> 0)
ORDER BY
PR.DOC_ID
这导致数据样本如下:
我需要过滤掉包含修正的承诺总和为0的所有Doc_ID。例如,Doc_ID 21162465SD541应该被过滤掉,因为Ammend_No 0,1和2的总和是0。
答案 0 :(得分:2)
如果您需要文档级别的信息,则只需在GROUP BY
中包含该信息:
SELECT PR.DOC_ID, Sum(LEDGER.COMMIT)
FROM LUFSMGR.APPRVL_CHAIN APPRVL_CHAIN JOIN
LUFSMGR.LEDGER LEDGER
ON LEDGER.DOC_ID = APPRVL_CHAIN.DOC_ID AND APPRVL_CHAIN.AMEND_NO = LEDGER.AMEND_NO JOIN
LUFSMGR.PR PR
ON PR.DOC_ID = LEDGER.DOC_ID AND AND LEDGER.AMEND_NO = PR.AMEND_NO
WHERE (PR.DOC_ID Like '2116%') AND
(LEDGER.ACCT_ID Like '25601 105300SD%') AND
(APPRVL_CHAIN.APPRVR_ROLE = 'Funds Manager')
GROUP BY PR.DOC_ID
HAVING Sum(LEDGER.COMMIT) <> 0
ORDER BY PR.DOC_ID;
注意:
JOIN
语法。简单规则:从不在FROM
子句中使用逗号。SELECT DISTINCT
与GROUP BY
一起使用几乎不是正确的事情。