从所有客户的实体中获得平衡

时间:2015-07-30 21:25:11

标签: sql postgresql

我有桌帐

id - name
1 - Lab
2 - Sara
3 - Jone

表格实体

id - credit - debit - value
1      1        3      10
1      1        2      20
1      3        1      5
1      2        1      3

我希望所有客户的余额都是输出:

Name - balance
Sara     17
Jone     5

2 个答案:

答案 0 :(得分:1)

select account.name, (plus.balance - minus.balance) as balance 
from accounts inner join
(select credit as id, sum(value) as balance from entities group by credit) as plus 
inner join 
(select debit as id, sum(value) as balance from entities group by debit) as minus 
on plus.id = minus.id and accounts.id = plus.id

解释 - 我正在从实体表中创建两个副本 - 一个用于汇总信用额度(每个ID),另一个用于汇总借方,然后将它们与accounts表连接以获取名称。不确定你对实体表中的id列做了什么,似乎是多余的。

答案 1 :(得分:0)

在第6行

中没有使用errur无效令牌')'
select "Accounts".name, (plus.balance - minus.balance) as balance 
from 
"Accounts" inner join
(select public.entities.accounts_id_credit as id, sum(value) as balance from public.entities group by public.entities.accounts_id_credit) as plus 
inner join 
(select public.entities.accounts_id_debit as id, sum(value) as balance from public.entities group by public.entities.accounts_id_debit) as minus
on plus.id = minus.id and "Accounts".id = plus.id