两张表的累计余额

Cumulative balance across two tables

我想从按日期排序的 2 个表中获取数据: 获取客户的累计余额

我想从中获取数据的 2 个表是我的表:transfers & trans_payments

转会:

ID        int   
cust_id   int   
tfrom     nvarchar(200) 
tto       nvarchar(200)
price     decimal(18, 2)
tax       decimal(18, 2)
final     Calculated 
tnumber   nvarchar(30)
note      nvarchar(MAX)
date      date

trans_payments:

ID       int
cust_id  int
value    decimal(18, 2)
method   nvarchar(30)
note     nvarchar(MAX)
date     date

假设我有以下数据:

转会:

ID    cust_id   final       date    
1      5        3000     22-09-2020  
2      5        1500     25-09-2020 
3      10       4000     28-09-2020

trans_payments:

ID    cust_id   value       date  
1      5        1000     22-09-2020
2      5        1500     23-09-2020
3      5        1000     01-10-2020
4      10       1000     28-09-2020
5      10       2000     01-10-2020

我想创建一个视图来显示客户对购买和付款的操作,如下所示:

客户 5:

cust_id   final    value    Balance    date      
5        3000        0       3000     22-09-2020 --- > Purchases 
5         0        1000      2000     22-09-2020 --- > payment
5         0        1500      500      23-09-2020 --- > payment
5        1500        0       2000     25-09-2020 --- > P
5         0        1000      1000     23-09-2020 --- > payment purchases  

最后一行是客户的最终余额

我试过这个:

CREATE VIEW customer_account_summary as 
WITH Tb0 as
( SELECT ID,date,cust_id,final,0'value' from transfers
        UNION
        SELECT ID,date,cust_id,0'final',value from trans_payments
)

, Tb1 as
( 
    SELECT ID,date,cust_id,final,value,Row_Number() over (order by date asc) as [OrderId]
        FROM    
            Tb0
)

SELECT TOP 1000000 T1.ID,T1.cust_id,T1.date,T1.final,T1.value,(Sum(T2.final) - Sum(T2.value)) as Balance FROM Tb1 as T1
            INNER JOIN
                Tb1 as T2
                ON T1.[OrderId] <= T2.[OrderId]
                Group By T1.ID,T1.cust_id,T1.date,T1.final,T1.value
                Order by [date] 

但我有一个问题,如果 2 个客户在同一天付款,付款将计算在同一日期付款的 2 个客户,我尝试添加 2 的 ID 以防止查询对数据进行分组但是我仍然面临天平的错误。

我怎样才能以正确的方式做到这一点?

我认为是 union all 和 window sum():

select cust_id, final, value, date,
    sum(balance) over(partition by cust_id order by date, seq) balance
from (
        select cust_id, final, 0, final balance, date, 0 from transfers
        union all
        select cust_id, 0, value, -value, date, 1 from trans_payments
) t (cust_id, final, value, balance, date, seq)
order by cust_id, date, seq

当两个表中都有给定日期的行时,这会将转移放在第一位。

Demo on DB Fiddle:

cust_id | final | value | date       | balance
------: | ----: | ----: | :--------- | ------:
      5 |  3000 |     0 | 2020-09-22 |    3000
      5 |     0 |  1000 | 2020-09-22 |    2000
      5 |     0 |  1500 | 2020-09-23 |     500
      5 |  1500 |     0 | 2020-09-25 |    2000
      5 |     0 |  1000 | 2020-10-01 |    1000
     10 |     0 |  2000 | 2020-01-01 |   -2000
     10 |  4000 |     0 | 2020-09-28 |    2000
     10 |     0 |  1000 | 2020-09-28 |    1000

您可以使用 where 子句来过滤给定的客户。