如何获得具有分组条件的行数

时间:2018-07-03 07:43:49

标签: mysql count

我想获取数量为> 0

的行数

没有计数功能我的查询

   SELECT pd.student_admission_id,

    sum(fcm.fee_amount)- coalesce((SELECT sum(ft.amount_paid) FROM   fee_transactions ft  where ft.student_id=pd.student_admission_id GROUP BY     ft.student_id), 0)  as due_amount

FROM fee_class_mapping fcm INNER JOIN student_present_class_details pd ON pd.class_id = fcm.class_id  GROUP BY  pd.student_admission_id;

结果

+----------------------+------------+
| student_admission_id | due_amount |
+----------------------+------------+
|                    1 |          0 |
|                    2 |      12000 |
|                    3 |      12000 |
+----------------------+------------+

我想获取谁的应付金额> 0

如何通过上述查询编写计数函数?

有人可以帮助我吗?谢谢!!

1 个答案:

答案 0 :(得分:1)

对于第一个查询,您可以使用类似的连接将其重写

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

要获取count_amount> 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