对于第一个查询,您可以使用如下的连接重写它
SELECT pd.student_admission_id,
SUM(fcm.fee_amount) - COALESCE(ft.amount_paid, 0) AS due_amount
FROM student_present_class_details pd
INNER JOIN fee_class_mapping fcm ON pd.class_id = fcm.class_id
LEFT JOIN(
SELECT student_id,SUM(ft.amount_paid) amount_paid
FROM fee_transactions
GROUP BY student_id
) ft ON ft.student_id=pd.student_admission_id
GROUP BY pd.student_admission_id
要获取到期金额为0的计数,可以将上述查询作为子查询包装。
SELECT COUNT(*)
FROM (
SELECT pd.student_admission_id,
SUM(fcm.fee_amount) - COALESCE(ft.amount_paid, 0) AS due_amount
FROM student_present_class_details pd
INNER JOIN fee_class_mapping fcm ON pd.class_id = fcm.class_id
LEFT JOIN(
SELECT student_id,SUM(ft.amount_paid) amount_paid
FROM fee_transactions
GROUP BY student_id
) ft ON ft.student_id=pd.student_admission_id
GROUP BY pd.student_admission_id
) t
WHERE t.due_amount > 0