我在gfee和netpay上得到了错误的价值。
SELECT s.id, s.name, c.name AS course_name,
s.open_bal AS open_balance, sum(i.amount) AS gross_fee,
sum(i.discount) AS discount, sum(i.amount) - sum(i.discount) AS net_payable,
SUM(r.reg_fee+r.tut_fee+r.other_fee) AS net_recieved,
(sum(i.amount) - sum(i.discount)) - SUM(r.reg_fee+r.tut_fee+r.other_fee) AS balance_due
FROM subscribers s
INNER JOIN courses c on c.id = s.course_id
LEFT JOIN invoices i on i.student_id = s.id
LEFT JOIN recipts r on r.student_id = s.id
GROUP BY s.id;
为什么会这样?
答案 0 :(得分:1)
问题的最可能原因是其中一个联接表中存在多个行。
由于您获得预期值的两倍(70000 vs 35000),我猜在courses
或recipts
表中有两行student_id=22
。
答案 1 :(得分:1)
SELECT s.id
, s.name
, c.name AS course_name
, s.open_bal AS open_balance
, igroup.gross_fee
, igroup.discount
, igroup.net_payableinvoices
, rgroup.net_recieved
, igroup.net_payableinvoices - rgroup.net_recieved
AS balance_due
FROM students s
INNER JOIN courses c
on c.id = s.course_id
LEFT JOIN
( SELECT i.student_id
, SUM(i.amount) AS gross_fee
, SUM(i.discount) AS discount
, SUM(i.amount) - sum(i.discount)
AS net_payableinvoices
FROM invoices i
GROUP BY i.student_id
) AS igroup
ON igroup.student_id = s.id
LEFT JOIN
( SELECT r.student_id
, SUM(r.reg_fee+r.tut_fee+r.other_fee)
AS net_recieved
FROM recipts r
GROUP BY r.student_id
) AS rgroup
ON rgroup.student_id = s.id
;
答案 2 :(得分:0)
70,000是双35,000的事实是一个非常重要的线索。你说的是SUM
,你得到的是你预期的两倍。这强烈表明您加入的行数是您认为的两倍。
如果不了解架构的详细信息,则很难具体说明,但如果您在receipts
中为invoices
中的每一行加入两个不同的行(对于此特定记录),则结束您的总和中包含两个35,000
个条目。不是你的想法。