0

我有三个名为:Student、StudentPayment 和 CreditAmount 的表。我想显示一个学生欠学校多少钱的结果。在 student 表中有一个名为 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 的总和,然后想从学生表的 TotalPayable 中减去它。任何人都可以帮我解决这个问题。提前致谢。

4

2 回答 2

5

Ajoin为右侧的每一行重复左侧的每一行。所以一个有两次付款和三个学分的学生最终会得到 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
于 2012-12-09T10:21:17.570 回答
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功能。

于 2012-12-09T10:16:42.000 回答