我正在使用以下查询从我的数据库的不同表中获取报告,请检查以下内容......
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 students 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;
发票
| id | student_id | amount | discount | dnt |
+----+------------+----------+----------+-------------+
| 2 | 22 | 35000 | 0 | 2011/01/01 |
+----+------------+----------+----------+-------------+
未从gross_fee和net_payable获取正确的值。
感谢。
答案 0 :(得分:2)
鉴于选择中的SUM
,我认为GROUP BY s.id
应该做到这一点。无论如何,GROUP BY
似乎缺失了:)
SELECT s.id, s.name, c.name AS course_name,
s.open_bal AS open_balance,
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 students 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;
修改
单独查询,允许检索所有发票的 gross_fee 和 net_payable
SELECT sum(amount) AS gross_fee,
sum(discount) AS discount,
sum(amount) - sum(discount) AS net_payable,
FROM invoices;
答案 1 :(得分:0)
是否有两个学生记录都获得了s.course_id的值?
你有从学生到课程的内心联系......
INNER JOIN课程c c.id = s.course_id
如果s.course_id在其中一个学生记录中为空,则查询将只返回一行。