在子查询返回多行的情况下求和值。 (我的用例是2行)

时间:2017-10-28 09:21:35

标签: mysql sql stored-procedures

我有多行来自查询。如何对这些行进行分组以汇总某些行的值并保留其余行。

set total_fees1 = (select (f.total_Fees2) from fee_Collection f where f.student_Id =minstudent_Id);
            set total_fees2 = (select (f.total_Fees3) from fee_Collection f where f.student_Id =minstudent_Id);
            set paid_amount1 = (select (f.paid_amount2) from fee_Collection f where f.student_Id =minstudent_Id);
            set paid_amount2 = (select (f.paid_amount3) from fee_Collection f where f.student_Id =minstudent_Id);

以上查询在某些情况下会返回2行。现在我必须在我获得超过1行的情况下添加paid_amount值,并获取total_fees字段的第一行值。

1 个答案:

答案 0 :(得分:0)

那将是:

set total_fees1 = (select (f.total_Fees2) from fee_Collection f where f.student_Id =minstudent_Id LIMIT 1);
        set total_fees2 = (select (f.total_Fees3) from fee_Collection f where f.student_Id =minstudent_Id LIMIT 1);
        set paid_amount1 = (select SUM(f.paid_amount2) from fee_Collection f where f.student_Id =minstudent_Id);
        set paid_amount2 = (select SUM(f.paid_amount3) from fee_Collection f where f.student_Id =minstudent_Id);