我有桌帐
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
答案 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