SQL Query故障过滤掉Sums

时间:2016-06-02 15:49:21

标签: sql

我需要帮助找出如何从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

这导致数据样本如下:

Sample Data

我需要过滤掉包含修正的承诺总和为0的所有Doc_ID。例如,Doc_ID 21162465SD541应该被过滤掉,因为Ammend_No 0,1和2的总和是0。

1 个答案:

答案 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 DISTINCTGROUP BY一起使用几乎不是正确的事情。