考慮賬戶和存款的數據庫:獲得總引用的表列
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的當前代碼。
我做錯了什麼,我怎麼能得到預期的總和?
你忘了銀行組 –