我有两张桌子stablestable和付款 我想获取在特定班级中按特定学期付款的学生人数 这是我的代码
SELECT classform, student_id, COUNT(student_id) as countreport_class
FROM studentstable s JOIN
(SELECT studentid
FROM payment
WHERE term= ? AND acayear=?
) AS pa
ON pa.studentid = s.student_id AND s.classform=?
GROUP BY s.student_id
但是结果是错误的。而是显示学生付款的次数。 我需要帮助。预先感谢。
答案 0 :(得分:1)
我期望这样的事情:
SELECT COUNT(*) as countreport_class
FROM studentstable s JOIN
payment p
ON p.studentid = s.student_id AND
p.term = ? AND p.acayear = ?
WHERE s.classform = ? ;
如果您希望查询返回单个数字,为什么要在select
中返回那么多列?
以上计算了付款次数。如果您希望获得付款的学生人数,请使用exists
:
SELECT COUNT(*) as countreport_class
FROM studentstable s
WHERE EXISTS (SELECT 1
FROM payment p
WHERE p.studentid = s.student_id AND
p.term = ? AND p.acayear = ?
) AND
s.classform = ? ;
答案 1 :(得分:0)
此查询
SELECT distinct studentid
FROM payment
WHERE term = ? AND acayear = ?
返回此学期至少付款1次的所有学生。
因此,如果将students表加入该查询并应用特定班级的条件,您将具有所需的条件:
SELECT COUNT(*) as countreport_class
FROM studentstable s INNER JOIN (
SELECT distinct studentid
FROM payment
WHERE term = ? AND acayear = ?
) AS pa ON pa.studentid = s.studentid
WHERE s.classform = ?
请参见demo