我有三个名为:Student,StudentPayment和CreditAmount的表。我想展示一个学生欠学校多少钱的结果。在学生表中有一个名为TotalPayable的列,它是要支付给学校的总金额,在StudentPayment中有一个名为TotalPaid的列,它是每次付款时的总付款,在CreditAmount表中有一个名为CreditAmount的列。是学校给予学生的豁免金额。所以我提出了一个问题:
SELECT Student.TotalPayableAmount -
Sum(StudentPayment.TotalPaid, CreditAmount.WaiverAmount) AS Total_Due
FROM (Student INNER JOIN StudentPayment ON Student.ID = StudentPayment.ID)
INNER JOIN CreditAmount ON (Student.ID = CreditAmount.ID) AND (Student.ID = CreditAmount.StudentID)
GROUP BY Student.ID, Student.TotalPayableAmount, CreditAmount.WaiverAmount
但它显示错误。
实际上我想制作TotalPaid和CreditAmount的SUM,然后想要从student表中的TotalPayable中减去它。请有人帮我这个。提前谢谢。
答案 0 :(得分:5)
对于右侧的每一行,join
重复左侧的每一行。因此,有两笔付款和三个学分的学生最终将获得6行。如果你sum
超过了那个,你就会得到错误的结果。
相反,您可以使用子查询来计算每个学生的总金额。由于子查询每个学生只返回一行,因此可以避免上面提到的行重复问题。例如;
select Student.ID
, Student.TotalPayableAmount -
iif(StudentPayment.TotalPaid is null, 0, StudentPayment.TotalPaid) -
iif(CreditAmount.WaiverAmount is null, 0, CreditAmount.WaiverAmount)
from (
Student
left join
(
select StudentID
, sum(Paid) as TotalPaid
from StudentPayment
group by
StudentID
) as StudentPayment
on StudentPayment.StudentID = Student.ID
)
left join
(
select StudentID
, sum(Waiver) as WaiverAmount
from CreditAmount
group by
StudentID
) as CreditAmount
on CreditAmount.StudentID = Student.ID
答案 1 :(得分:2)
您需要单独获取每个表的总和,然后按学生ID加入。
SELECT Student.TotalPayableAmount - Nz(sumTotalPaid,0) - Nz(sumCreditAmount,0)
FROM (Student
LEFT JOIN (
SELECT ID, Sum(TotalPaid) AS sumTotalPaid
FROM StudentPayment
GROUP BY StudentPayment.ID
) AS sum1
ON Student.ID = sum1.ID)
LEFT JOIN (
SELECT ID, Sum(CreditAmount) AS sumCreditAmount
FROM CreditAmount
GROUP BY CreditAmount.ID
) AS sum2
ON Student.ID = sum2.ID
注意:如果您是通过外部连接(DAO,ADO,ADO.NET)执行此操作,则无法使用Nz
功能。