MySQL -从另一个表求和

ulydmbyx  于 2023-02-15  发布在  Mysql
关注(0)|答案(2)|浏览(116)

我想运行一个包含另一个表的和的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
mklgxw1f

mklgxw1f1#

试试看

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演示

aij0ehis

aij0ehis2#

您需要创建子查询来隔离每个SUM,否则您将返回每个余额的SUM,而不是每个余额的SUM,并且它将是一行,而不是每个帐户的一行。

SELECT 
     a.account_name,
    (
      SELECT SUM(i.balance) 
      FROM tblinvoices AS i 
      WHERE a.account_id = i.tblaccount_account_id
    ) AS balance
FROM tblaccounts AS a;

相关问题