我试图创建一个MySQL查询以返回数据库中每个帐户的所有语句余额的总和。查询如下所示:
SELECT SUM(balance), handle FROM statement_versions INNER JOIN statements ON statement_versions.statement_id = statements.id INNER JOIN accounts ON statements.account_id = accounts.id;
当我这样做时,它只返回一行,其中有一个总余额和一个帐户(ID为1的帐户)。我想要的是退还所有帐户的对帐单余额。我将如何实现呢?
您可能需要按某种方式分组handle(我想这与帐户ID有关?),否则MySQL将从您的中选择SUM 所有 值JOIN。添加GROUP BY子句会使SUM。中列的每个不同值发生GROUP BY。将查询更改为:
handle
SUM
JOIN
GROUP BY
SELECT SUM(balance), handle FROM statement_versions INNER JOIN statements ON statement_versions.statement_id = statements.id INNER JOIN accounts ON statements.account_id = accounts.id GROUP BY handle;
如果handle与不相关,accounts.id并且您想要按进行分组accounts.id,则将查询更改为:
accounts.id
SELECT SUM(balance), accounts.id FROM statement_versions INNER JOIN statements ON statement_versions.statement_id = statements.id INNER JOIN accounts ON statements.account_id = accounts.id GROUP BY accounts.id;