gpt4 book ai didi

mysql - 为什么 MySQL SUM 查询只返回一行?

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:38 26 4
gpt4 key购买 nike

我正在尝试创建一个 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 all 从您的 JOIN 中选择的值。添加 GROUP BY 子句会使 SUM 发生在 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;

如果 handleaccounts.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;

关于mysql - 为什么 MySQL SUM 查询只返回一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com