获取基于外键的值

时间:2014-04-29 22:09:49

标签: android sql sqlite

我有两张桌子:

Acounts:

ID    Name
1     cash
2     bank
3     credit card

交易

ID   accounts_id   details    income    expenses
1    1              abc        1000        0
2    1              xyz           0      500
3    2              avc         200        0

我想要的是获取帐户表中所有帐户的收入和费用总和列(即使该帐户的交易表中没有记录)

必需的输出:

account_id    total_income    total_expenses
 1                 1000             500
 2                  200               0
 3                    0               0  

我在sql中尝试的是什么:

select account_id,coalesce (sum(income),0) as total_income,coalesce(sum(expenses),0) as total_expenses from transactions where account_id in (select id as accounts_id from accounts) group by account_id

以上查询给出的内容:

account_id    total_income    total_expenses
 1                 1000             500
 2                  200               0

ID为3的帐户未包含在结果中..

我知道我做错了什么......或者可能完全错了..

提前致谢。

2 个答案:

答案 0 :(得分:0)

您需要获取帐户表中的所有帐户。为此,您需要join,特别是outer join

select a.account_id, coalesce(sum(t.income),0) as total_income,
       coalesce(sum(t.expenses),0) as total_expenses
from accounts a left join
     transactions t
     on a.account_id = t.account_id
group by a.account_id;

您在where子句中尝试执行此操作是违反直觉的。 where子句过滤值,因此减少了行数;它无法增加数量。

答案 1 :(得分:0)

          WITH TEMP AS
          (
            SELECT A.ID,T.*
            FROM ACCOUNTS A INNER JOIN TRANSACTIONS T 
            ON A.ID=T.ID
          )
          SELECT ACCOUNT_ID,SUM(INCOME) AS INCOME,SUM(EXPENSE) AS EXPENSE FROM TEMP
          GROUP BY ACCOUNT_ID;