【问题标题】:How to get balance from two SQL table debit and credit dynamically如何动态从两个 SQL 表借方和贷方中获取余额
【发布时间】:2020-06-19 00:51:42
【问题描述】:

客户表

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.customerid=credit.customer 的RIGHT JOIN credit
    在customers.customerid=debit.customer GROUP BY customers.customerid,debit.year
上正确加入借方

查询结果

year|   customer |  sum(debit)| sum(credit)| Balance    
2020 |  ac1001   |  48000     | 42000      | 6000
2020 |  ac1002   |  8000      | 6000       | 2000

但我需要的是下面这张表,谢谢

预期结果

year|   customer |  sum(debit)| sum(credit)| Balance    
2019 |  ac1001   |  4000      | 3000       | 1000
2020 |  ac1001   |  4000      | 4000       |  0
2020 |  ac1002   |  4000      | 4000       |  0

【问题讨论】:

    标签: sql


    【解决方案1】:

    union这两个表然后聚合。您可以使用累积和来计算余额:

    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;
    

    【讨论】:

    • 我还有一个问题,贷方表和借方表中的个别金额没有显示,我可以得到一些帮助
    • @SamuelMomoh 。 . .这是相同的想法,只是更多的列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多