我正在嘗試在 SQL 服務器上構建一個報告,該報告將提供客戶的平均到期結算天數。這是我要從中生成報告的示例表
| 顧客 | 日期 | 借方 | 信用 |
|---|---|---|---|
| 美國廣播公司 | 2021-04-01 | 10000 | 0 |
| 美國廣播公司 | 2021-04-08 | 0 | 3000 |
| 美國廣播公司 | 2021-05-02 | 1000 | 1000 |
| 美國廣播公司 | 2021-06-09 | 0 | 2000 |
| 美國廣播公司 | 2021-07-10 | 2000 | 1000 |
| 美國廣播公司 | 2021-08-11 | 0 | 4000 |
| 美國廣播公司 | 2021-09-10 | 0 | 3000 |
在這里,我試圖生成一份報告,說明客戶 abc 已經結清了他在 2021 年 4 月 1 日所欠的 10000 美元的欠款,于 2021 年 8 月 11 日結清,客戶花了 132 天時間才結清,第二次到期(1000 美元) ) 2021 年 5 月 2 日的欠款于 2021 年 8 月 21 日清償,耗時 101 天,而 2021 年 7 月 10 日的 2000 美元到期款項于 2021 年 9 月 10 日清償,耗時 62 天。
所以想要的輸出是
| 顧客 | 結算天數 |
|---|---|
| 美國廣播公司 | 132 |
| 美國廣播公司 | 101 |
| 美國廣播公司 | 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
我被困在這里不知道如何進一步
uj5u.com熱心網友回復:
使用視窗函式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<>小提琴演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447889.html
上一篇:SQL試圖用*替換中間字符
