需要帮助以获得以下查询

时间:2012-02-17 13:35:10

标签: mysql sum

我有三个表customer,customer_account,account_transaction

表结构如下 -

客户

Id,
Branch,
Name

...

customer_account

Id,
Cust_id,
Loanamout,
EMI

account_transaction

ID,
account_id,
amount,
date

我需要以贷款计数,贷款总额和特定分行收到的emi总和的形式获得分支机构明智的详细信息。下面是我当前的查询 -

SELECT
  count(s.id) as cntloan, 
  SUM(s.Loanamout)
  (
    SELECT SUM(amount) 
    FROM account_transaction i
    WHERE s.id = i.account_id
  ) AS curbal 
From
   customer as c,
   customer_account as s
where c.branch = 1 and s.cust_id = c.id 

给出了贷款数额和贷款额度的期望结果。但没有给出客户支付的正确的EMI总和

任何人都可以帮助我。

非常感谢你

1 个答案:

答案 0 :(得分:0)

此SQL具有聚合函数,例如count和sum,因此如果没有group by,这将无效。

SELECT customer.id,
COUNT(customer_account.id) as cntloadn,
SUM(customer_account.loan) as loan,
SUM(account_transaction.amount)
FROM customer
JOIN customer_account ON customer_account.cust_id = customer.id
JOIN account_transaction ON account_transaction.account_id = customer_account.id
GROUP BY customer.id