在查询中使用别名来获得总和

时间:2015-09-17 08:41:25

标签: mysql

我在另一个参数中使用别名来获取累积总和但是收到错误。如何在查询中添加别名。

SET @total=0;
SET @amountDue=0;

SELECT cs.customer_name,l.paid_date, IF(@total=0,((pl.total_amount)-
(pl.installment_amount_month)*( pl.total_installments))
,( pl.installment_amount_month)) AS AmountDue
      ,@amountDue := @amountDue + AmountDue as ComulativeDue,

 l.amount AS AmountPaid,
  @total := @total +l.amount AS comulativePaid,
 (@total/@amountDue ) as percentage
 FROM payments_details l join payment_loan pl on (pl.loan_id=l.loan_id) join
 customer cs on (cs.customer_id=l.customer_id)
 WHERE l.customer_id=cs.customer_id and pl.loan_id=l.loan_id
 GROUP BY l.paid_date ORDER BY  l.paid_date ;

1 个答案:

答案 0 :(得分:0)

除非您尝试在外部选择查询中访问它,否则您无法直接使用这样的列别名。您必须使用整个表达式来计算AmoutnDue,而不是

SELECT cs.customer_name,l.paid_date, IF(@total=0,((pl.total_amount)-
(pl.installment_amount_month)*( pl.total_installments))
,( pl.installment_amount_month)) AS AmountDue
      ,@amountDue := @amountDue + IF(@total=0,((pl.total_amount)-
(pl.installment_amount_month)*( pl.total_installments))
,( pl.installment_amount_month)) as ComulativeDue,