如何动态地从两个SQL表debit和credit中获取平衡
客户表如何动态地从两个SQL表debit和credit中获取平衡,sql,Sql,客户表 id | name | customerid 1 | Philip James | ac1001 2 | Frank Mathew | ac1002 信用表 id| year | customer | amount 1 | 2020 | ac1001 | 1000 2 | 2020 | ac1001 | 1000 3 | 2020 | ac1001 | 1000 4 | 2020 | ac1001 | 10
id | name | customerid
1 | Philip James | ac1001
2 | Frank Mathew | ac1002
信用表
id| year | customer | amount
1 | 2020 | ac1001 | 1000
2 | 2020 | ac1001 | 1000
3 | 2020 | ac1001 | 1000
4 | 2020 | ac1001 | 1000
5 | 2019 | ac1001 | 1000
6 | 2019 | ac1001 | 2000
7 | 2020 | ac1002 | 2000
8 | 2020 | ac1002 | 2000
借记表
id| year | customer| amount
1 | 2020 | ac1001 | 1000
2 | 2020 | ac1001 | 1000
3 | 2020 | ac1001 | 1000
4 | 2020 | ac1001 | 1000
5 | 2019 | ac1001 | 2000
6 | 2019 | ac1001 | 2000
7 | 2020 | ac1002 | 2000
8 | 2020 | ac1002 | 2000
我试图动态地获得每个客户在这一年的余额,我尝试使用这个;
SELECT debit.year,customers.name,customers.customerid,SUM(debit.amount),SUM(credit.amount),
SUM(COALESCE((debit.amount),0)-COALESCE((credit.amount),0))AS balance FROM
customers
RIGHT JOIN credit ON customers.customerid=credit.customer
RIGHT JOIN debit ON customers.customerid=debit.customer GROUP BY customers.customerid,debit.year
但我需要的是下表,谢谢
预期结果
year| customer | sum(debit)| sum(credit)| Balance
2019 | ac1001 | 4000 | 3000 | 1000
2020 | ac1001 | 4000 | 4000 | 0
2020 | ac1002 | 4000 | 4000 | 0
联合
两个表,然后进行聚合。您可以使用累计总和来计算余额:
select year, customer, sum(amount) as amount_in_year,
sum(sum(amount)) over (partition by customer order by year) as end_of_year_balance
from ((select id, year, customer, amount
from credit
) union all
(select id, year, customer, - amount
from debit
)
) cd
group by year, customer;
编辑:
经修订的问题:
select year, customer, sum(credit) as sum_credit, sum(debit) as sum_debit,
sum(sum(credit - debit)) over (partition by customer order by year) as end_of_year_balance
from ((select id, year, customer, amount as credit, 0 as debit
from credit
) union all
(select id, year, customer, 0 as credit, amount as debit
from debit
)
) cd
group by year, customer;
我还有一个问题,贷方表和借方表中的个人金额没有显示出来,我能得到一些帮助吗that@SamuelMomoh . . . 这是相同的想法,只是更多的专栏。
select year, customer, sum(credit) as sum_credit, sum(debit) as sum_debit,
sum(sum(credit - debit)) over (partition by customer order by year) as end_of_year_balance
from ((select id, year, customer, amount as credit, 0 as debit
from credit
) union all
(select id, year, customer, 0 as credit, amount as debit
from debit
)
) cd
group by year, customer;