我試圖從一個包含所有歷史記錄的交易表中創建一個月度銀行賬戶報表。 我希望有第一行的期初餘額,然後使用遞歸cte在當時更新的餘額。 我知道這也可以通過表更新來完成,但遞歸是我正在尋找的。使用遞歸cte的SQL月度報表
表結構會是這樣:
declare @temp table (date datetime,tran_id int,cust_id int,tran_type char,amount int)
insert into @temp values('2017-06-06 22:05:10.703',1,1,'c',700),
('2017-06-12 22:05:10.703',2,1,'d',100),('2017-06-20 22:05:10.703',3,1,'c',200),
('2017-06-26 22:05:10.703',4,1,'d',450),(getdate()+1,5,1,'d',200),
(getdate()+2,6,1,'d',200),(getdate()+3,7,1,'c',500),
(getdate()+4,8,1,'d',300),(getdate()+5,9,1,'d',200),
('2017-06-18 22:05:10.703',12,1,'d',100)
所以在這裏有交易的6個月和7 當月的期初餘額將在6月的所有交易將被用作總和錨點以獲得遞歸平衡。 現在我想選擇查詢將date,tran_id,cust_id,credit,debit,balance作爲結果集。
所以,如果表中有類似的數據:
date tran_id cust_id tran_type amount
2017-06-06 22:05:10.703 1 1 c 700
2017-06-12 22:05:10.703 2 1 d 100
2017-06-20 22:05:10.703 3 1 c 200
2017-06-26 22:05:10.703 4 1 d 450
2017-07-08 16:34:24.817 5 1 d 200
2017-07-09 16:34:24.817 6 1 d 200
2017-07-10 16:34:24.817 7 1 c 500
2017-07-11 16:34:24.817 8 1 d 300
2017-07-12 16:34:24.817 9 1 d 200
2017-06-18 22:05:10.703 12 1 d 100
The monthly statement for month 7 should be like:
opening balance of 250
date tran_id cust_id credit debit balance
2017-07-08 16:40:56.810 5 1 NULL 200 50
2017-07-09 16:40:56.810 6 1 NULL 200 -150
2017-07-10 16:40:56.810 7 1 500 NULL 350
2017-07-11 16:40:56.810 8 1 NULL 300 -50
2017-07-12 16:40:56.810 9 1 NULL 200 -250
我一直在使用遞歸CTE和總結窗口函數嘗試,但它並沒有被排平衡給予持續的平衡只是一個排。
同樣在cte中使用聚合函數也是如此。
;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
),
cte2 as
(
select * from cte
union all
select t.cust_id,amount+[opening balance] as 'balance1' from @temp t join
cte2 c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte2
OR
;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
union all
select t.cust_id,SUM(amount+[opening balance]) as 'balance1' from @temp t
join cte c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte
option (MAXRECURSION 1000)
我在想什麼?
你能與預期的結果 –
添加表 –
的SQL Server版本使用的是 –