gpt4 book ai didi

mysql - 总和在查询中相乘

转载 作者:行者123 更新时间:2023-11-30 23:30:53 27 4
gpt4 key购买 nike

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

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

最佳答案

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_PAIDVIOLATION_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为零。

关于mysql - 总和在查询中相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10722285/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com