从同一个表中汇总2个MySQL字段中的记录并将其用作条件

时间:2013-06-07 08:05:03

标签: mysql

我正在开展一个项目,其中一部分要求我能够显示已完成还款的个人的记录。要完成还款,他们必须每月还款和一次性付款。因此,我希望能够将个人的还款金额字段和lumpsum字段中的记录汇总,由他的贷款人识别。这是样本表

还款表

loanid  |  repayment_amount  | lumpsum  | memberid
  21             20,000           30,000      45

贷款表

loanid  |  amountdue  | memberid
  21        40,000         45

会员表

memberid  |  first_name  | middle_name  | last_name
  21             John        Tom            Bun

这是我在MySQL中编写的SQL查询

SELECT first_name, last_name
FROM repayment,loan, members
WHERE repayment.loanid = loan.loanid AND repayment.memberid = members.memberid 

WHERE (SUM(amount)+ SUM(lumpsum)) >= loan.amountdue

我似乎无法显示我想要的内容,这是一个人数列表,其中金额和总量的总和大于应付金额。

请帮助

2 个答案:

答案 0 :(得分:1)

SELECT first_name, last_name
FROM repayment,loan, members
WHERE
 repayment.loanid = loan.loanid AND 
 repayment.memberid = members.memberid 
GROUP BY first_name, last_name
HAVING
 SUM(repayment.repayment_amount) + SUM(repayment.lumpsum) >= SUM(loan.amountdue)

答案 1 :(得分:0)

SELECT m.first_name, m.last_name
FROM repayment r,loan l, members m
WHERE r.loanid = l.loanid AND r.memberid = m.memberid 
HAVING (SUM(r.repayment_amount)+ SUM(r.lumpsum)) >= l.amountdue