按帐户对所有帐户进行SUM交易

时间:2014-06-20 13:27:40

标签: mysql

我跟踪MySQL中的交易,我试图整理一份报告,向我展示给定月份每个帐户的总数。现在,我可以让它向我显示任何有交易的帐户的总计,但问题是我还需要它还可以返回没有交易的帐户,当前查询不会这样做。

我的数据库设计有两个表,一个用于帐户(每个帐户都有名称和ID),以及一个事务表(包含id,accountId,日期和金额字段)。我当前的查询如下所示:

SELECT 
    SUM(transactions.amount) AS monthly_total,
    accounts.id AS account_id,
    accounts.name AS account_name
FROM accounts
LEFT JOIN transactions ON transactions.accountId = accounts.id
WHERE transactions.date BETWEEN '2014-01-01' AND '2014-01-31'
GROUP BY accounts.id
ORDER BY accounts.name

就像我说的,这个查询有效,只是它没有返回所有帐户。它仅返回记录了交易的帐户。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您的WHERE条件正在过滤掉没有交易的帐户。

尝试 -

SELECT 
    SUM(transactions.amount) AS monthly_total,
    accounts.id AS account_id,
    accounts.name AS account_name
FROM accounts
LEFT JOIN transactions ON transactions.accountId = accounts.id 
        AND transactions.date BETWEEN '2014-01-01' AND '2014-01-31'
GROUP BY accounts.id
ORDER BY accounts.name

答案 1 :(得分:0)

试试这个

...
sum(ifnull(transactions.amount, 0))
...
right JOIN transactions ON transactions.accountId = accounts.id
...