2014-02-21 79 views
0

考慮賬戶和存款的數據庫:獲得總引用的表列

CREATE TABLE accounts (
    id int not null primary key, 
    name varchar(63) 
); 

CREATE TABLE deposits (
    id int not null primary key, 
    account int references accounts(id), 
    dollars decimal(15, 2), 
    status enum('pending','complete') 
); 


insert into accounts values 
(0, 'us'), 
(1, 'europe'), 
(2, 'asia'); 

insert into deposits values 
(0, 0, 10, 'pending'), 
(1, 0, 20, 'complete'), 
(2, 1, 100, 'complete'), 
(3, 1, 200, 'pending'), 
(4, 1, 300, 'complete'), 
(5, 2, 1000, 'pending'); 

我想獲得一個總的每個銀行的所有complete存款,這是預期的結果:

+--------+-----+ 
| us  | 20 | 
| europe | 400 | 
| asia | 0 | 
+--------+-----+ 

這是我嘗試過的SQL,但預期它不工作:

SELECT 
    a.name, SUM(d.dollars) 
FROM 
    accounts a 
    INNER JOIN 
    deposits d ON (a.id = d.account AND d.status='complete'); 

這是RESU它給出了:

+--------+-----+ 
| us  | 420 | 
+--------+-----+ 

Here is an SQLfiddle的當前代碼。

我做錯了什麼,我怎麼能得到預期的總和?

+0

你忘了銀行組 –

回答

1

試試這個

SELECT 
a.name, coalesce(SUM(d.dollars),0) as sums 
FROM 
accounts a 
left JOIN 
deposits d ON (a.id = d.account AND d.status='complete') 
group by a.name 
order by sums desc 

你應該使用LEFT JOIN,你應該使用GROUP BY也。

LOOK DEMO

1

你應該a.name(或者甚至a.id)和LEFT OUTER JOIN使用分組(如果你想獲得非現值)。

編輯:

SELECT 
    a.name, SUM(d.dollars) 
FROM 
    accounts a 
    LEFT OUTER JOIN 
    deposits d ON (a.id = d.account AND d.status='complete') 
GROUP BY a.name; 
+0

@Grijesh Chauhan,請參閱http://sqlfiddle.com/#!2/ce81f/9 – bodi0

1

嘗試此查詢:

SELECT 
a.name, IF(SUM(d.dollars) IS NULL, 0, SUM(d.dollars)) 
FROM 
    accounts a 
    LEFT JOIN 
    deposits d ON (a.id = d.account AND d.status='complete') 
GROUP BY a.name ORDER BY a.id; 
1

通過參加與存款賬戶只確保你總結美元鏈接到一個賬戶存款。如果你還想通過賬戶名稱進行分組,或者甚至賬戶ID,那麼你會得到一個總和/銀行。