求和值乘以记录数

时间:2015-10-19 12:04:13

标签: sql oracle

我在查询表格中上个月的付款总额和帐户对帐单。我使用以下查询来执行此操作

SELECT DA.ID, DDO.CODE, COALESCE(SUM(FPP.AMOUNT_IN_DEFAULT_CURRENCY),0) AS PAYMENTS,SUM(FAT.AMOUNT_IN_DEFAULT_CURRENCY) as STATEMENTS
    FROM DIM_ACCOUNT DA
        JOIN DIM_DATA_OWNER DDO ON DA.DATA_OWNER_ID = DDO.ID
        LEFT JOIN FACT_AS_TRANSACTION FAT ON DA.ID = FAT.ACCOUNT_ID
        JOIN DIM_DATE DD ON FAT.VALUE_DATE_ID = DD.ID
        LEFT JOIN FACT_PAY_PAYMENT FPP ON DA.ID = FPP.ORDERING_ACCOUNT_ID
        JOIN DIM_PAY_PAYMENT_METHOD DPPM ON FPP.PAYMENT_METHOD_ID = DPPM.ID
    WHERE DD.CAL_DATE >= TO_DATE('2015-09-19', 'YYYY-MM-DD')
        AND FPP.CREATION_DATE >= TO_DATE('2015-09-19', 'YYYY-MM-DD')
        AND DPPM.DIRECT_DEBIT_FLAG = 'N' 
        AND FAT.DEBIT_CREDIT_MARK = 'Debit'
    GROUP BY DA.ID, DDO.CODE
    HAVING SUM(FAT.AMOUNT_IN_DEFAULT_CURRENCY) != 0;

我加了3笔钱:

  

付款金额为2500

     

付款B金额2500

     

付款金额为2000

     

付款D金额500

我希望总共可以达到7500.但是当我执行此查询时,我得到30000.这与7500 * 4相同(我的付款表中有4条记录)。我想我可能会加入一些错误的东西。问题是什么?

1 个答案:

答案 0 :(得分:0)

在哪里打破左边所以它只是加入
或者如果您将条件提交到联接中,则可以执行左侧 这样的两个总和很少起作用,因为它们互相给出了重复的行 取出组,只需选择值,您将看到任何重复项 FAT中的4行将为您提供FPP中的4行 尝试两个单独的,看看你是否得到了正确的答案

SELECT DA.ID, DDO.CODE
     , COALESCE(SUM(FPP.AMOUNT_IN_DEFAULT_CURRENCY),0) AS PAYMENTS
     , SUM(FAT.AMOUNT_IN_DEFAULT_CURRENCY)             as STATEMENTS
  FROM DIM_ACCOUNT DA
  JOIN DIM_DATA_OWNER DDO 
        ON DA.DATA_OWNER_ID = DDO.ID
  JOIN FACT_AS_TRANSACTION FAT 
        ON DA.ID = FAT.ACCOUNT_ID
       AND FAT.DEBIT_CREDIT_MARK = 'Debit'
  JOIN DIM_DATE DD 
        ON FAT.VALUE_DATE_ID = DD.ID
       AND DD.CAL_DATE >= TO_DATE('2015-09-19', 'YYYY-MM-DD')
  JOIN FACT_PAY_PAYMENT FPP 
        ON DA.ID = FPP.ORDERING_ACCOUNT_ID 
       AND FPP.CREATION_DATE >= TO_DATE('2015-09-19', 'YYYY-MM-DD')     
  JOIN DIM_PAY_PAYMENT_METHOD DPPM 
        ON FPP.PAYMENT_METHOD_ID = DPPM.ID       
       AND DPPM.DIRECT_DEBIT_FLAG = 'N'              
 GROUP BY DA.ID, DDO.CODE
HAVING SUM(FAT.AMOUNT_IN_DEFAULT_CURRENCY) != 0;