代码之家  ›  专栏  ›  技术社区  ›  bharath

如何获取条件为“分组依据”的行数

  •  1
  • bharath  · 技术社区  · 7 年前

    我想知道行数,金额是多少 >零

    带out count函数my query

       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

    如何使用上述查询编写count函数?

    有人能帮我吗?谢谢你!.

    1 回复  |  直到 7 年前
        1
  •  1
  •   M Khalid Junaid    7 年前

    对于第一个查询,您可以使用如下的连接重写它

    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