2012-02-17 29 views
0

我有三個表的客戶,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的正確金額

任何人都可以幫助我解決這個問題。

非常感謝你

+2

我在該查詢中看不到EMI。你在哪裏工作/檢索它? – 2012-02-17 13:37:48

+0

這是期中考試嗎?這是一個非常基本的數據庫類問題。 – Churk 2012-02-17 13:38:17

+0

格式化時,我注意到一個缺少的逗號讓子查詢感到厭煩。我們認爲這是一個錯字... – 2012-02-17 13:39:14

回答

0

此SQL具有聚集功能,如數量和金額,所以沒有一組通過,這是行不通的。

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