客户余额账龄报告

Customer Balance Aging Report

我正在尝试在 SQL 服务器上生成报告,该报告将提供客户的平均到期结算天数。 这是示例 table,我想从中生成报告

Customer Date Debit Credit
abc 2021-04-01 10000 0
abc 2021-04-08 0 3000
abc 2021-05-02 1000 1000
abc 2021-06-09 0 2000
abc 2021-07-10 2000 1000
abc 2021-08-11 0 4000
abc 2021-09-10 0 3000

在这里,我试图生成一份报告,表明客户 abc 已结清他在 2021-04-01 欠下的 10000 美元,已于 2021-08-11 结清,客户用了 132 天来结清2021 年 5 月 2 日欠下的第二笔款项(1000 美元)在 2021 年 8 月 21 日清偿,用时 101 天,2021 年 7 月 10 日欠下的 2000 美元在 2021 年 9 月 10 日清偿,用时 62 天清除。
所以所需的输出是

Customer settlement_days
abc 132
abc 101
abc 62

我尝试使用 SQL 游标来执行此操作,但在得到结果 132 后我被卡住了。请在下面找到代码

begin
        declare @date as date        
        declare @debit as int
        declare @debit1 as int=0
        declare @credit as int
        declare @credit1 as int=0
        declare @balance as int=0
        declare @date1 as date
        declare @i as int=0
        declare @count as int
        declare @k as int=0


        declare closing scroll cursor for
        select convert(date,date),debit,credit from samples
        select  @count= count(debit) from samples
        open closing
        fetch next from closing into @date, @debit, @credit ;
        while @@FETCH_STATUS=0
        begin
        set @balance=@credit-@debit
        set @date1=@date
        set @debit1=@debit
        while @@FETCH_STATUS=0 

        begin
                set @balance=@balance+@credit
                set @credit1=@credit1+@credit
                set @i=@i+@debit
                if (@k<=@debit1)
                begin
                    set @k=@k+@debit
                end
                
                if @balance>0
                begin 
                        print(datediff(day,@date1,@date))
                        print (@credit1-@debit1)
                        print (@k)
                        break
        
                end
                fetch next from closing into @date, @debit, @credit;
                
        end
        fetch next from closing into @date, @debit, @credit;
        end
        
        close closing
        deallocate closing
end

我被困在这里不知道如何继续

使用 window 函数 sum() over () 求总借方和总贷方的累计总和。之后找到总贷方 >= 总借方的最早日期。那是结算日

with 
debit as
(
    select  *, 
            -- cumulative sum
            sum(Debit) over(partition by Customer order by [Date]) as Dr
    from    samples s
    where   Debit   > 0
),
credit as
(
    select  *, 
            -- cumulative sum
            sum(Credit) over(partition by Customer order by [Date]) as Cr
    from    samples s
    where   Credit  > 0
)
select  *, datediff(day, dr.[Date], cr.[Date]) as SettlementDays
from    debit dr
        cross apply
        (
            select  top 1 cr.[Date]
            from    credit cr
            where   cr.Customer  = dr.Customer
            and     cr.Cr       >= dr.Dr
        ) cr
order by dr.Customer, dr.[Date]

db<>fiddle demo