1

我正在处理 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;

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

4

1 回答 1

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表的连接。如果您使用聚合函数删除 Group By 和列,您可能会看到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用零替换。

于 2012-05-23T22:14:33.233 回答