我想运行一个select语句,其中包含另一个表的总和。我知道我可能需要设置一个连接,但我不确定如何处理它。
我想选择一个帐户列表然后获取余额(另一个表中的总和) 这是我一直在进行的想法,但显然它不正确。
SELECT
account_name
FROM
tblaccounts
JOIN (
SELECT
SUM(balance) AS account_balance
FROM
tblinvoices
) t ON t.account_id = tblaccount_account_id
WHERE
tblaccounts.account_id = 1
期望的输出
Name | balance ------------------ Account1 50 Account2 100
答案 0 :(得分:4)
尝试
SELECT account_name, SUM(balance) balance
FROM tblaccounts a LEFT JOIN tblinvoices i
ON a.account_id = i.tblaccount_account_id
WHERE a.customer_id = 1
GROUP BY account_id
输出:
| ACCOUNT_NAME | BALANCE | -------------------------- | Account1 | 50 | | Account2 | 100 |
这是 SQLFiddle 演示