总和在查询中成倍增加

时间:2012-05-23 14:41:20

标签: mysql

我正在为家庭作业解决2个问题,经过几个小时我刚刚解决了这两个问题,我的最后一个问题是我的两个查询都返回了双倍的数值而不是单个。

这就是我所拥有的:

SELECT SUM(P.AMT_PAID) AS TOTAL_PAID, C.CITATION_ID, C.DATE_ISSUED, SUM(V.FINE_CHARGED) AS TOTAL_CHARGED
FROM PAYMENT P, CITATION C, VIOLATION_CITATION V
WHERE V.CITATION_ID = C.CITATION_ID
AND C.CITATION_ID = P.CITATION_ID
GROUP BY C.CITATION_ID;

和我的另一个:

SELECT C.CITATION_ID, C.DATE_ISSUED, SUM(V.FINE_CHARGED) AS TOTAL_CHARGED, SUM(P.AMT_PAID) AS TOTAL_PAID, SUM(V.FINE_CHARGED) - SUM(P.AMT_PAID) AS TOTAL_OWED
FROM (CITATION C)
LEFT JOIN VIOLATION_CITATION V
ON V.CITATION_ID = C.CITATION_ID
LEFT JOIN PAYMENT P
ON P.CITATION_ID = C.CITATION_ID
GROUP BY C.CITATION_ID
ORDER BY TOTAL_OWED DESC;

我确信我会忽略一些东西。如果其他人可以告诉我我哪里出错了,那将是一个很大的帮助。

1 个答案:

答案 0 :(得分:0)

Select Sum(P.Amt_Paid) As Total_Paid, C.Citation_Id
    , C.Date_Issued, Sum(V.Fine_Charged) As Total_Charged
From Payment P
    Join Citation C
        On C.Citation_Id = P.Citation_Id
    Join Violation_Citation V
        On V.Citation_Id = C.Citation_Id
Group By C.Citation_Id

首先,您应该使用JOIN语法,而不是使用以逗号分隔的表列表。它使阅读更容易,更标准化,并有助于通过忽略过滤条款来防止问题。

其次,总和过大的最可能原因是由于加入VIOLATION_CITATION表。如果您删除分组依据和具有汇总功能的列,您可能会看到P.AMT_PAID的每个实例都重复VIOLATION_CITATION。也许,以下将解决问题:

Select Coalesce(PaidByCitation.TotalAmtPaid,0) As Total_Paid
    , C.Citation_Id, C.Date_Issued
    , Coalesce(ViolationByCitation.TotalCharged,0) As Total_Charged
    , Coalesce(ViolationByCitation.TotalCharged,0)
        - Coalesce(PaidByCitation.TotalAmtPaid,0) As Total_Owed
From Citation As C
    Left Join   (
                Select P.Citation_Id, Sum( P.Amt_Paid ) As TotalAmtPaid
                From Payment As P
                Group By P.Citation_Id
                ) As PaidByCitation
        On PaidByCitation.Citation_Id = C.Citation_Id
    Left Join   (
                Select V.Citation_Id, Sum( V.Find_Charged ) As TotalCharged
                From Violation_Citation As V
                Group By V.Citation_Id
                ) As ViolationByCitation
        On ViolationByCitation.Citation_Id = C.Citation_Id

使用Coalesce是为了确保如果左连接不返回给定Citation_ID值的行,则我们将Null替换为零。