【发布时间】:2017-12-11 15:47:36
【问题描述】:
我正在尝试从包含所有历史记录的交易表中创建每月银行帐户对帐单。 我希望将期初余额作为第一行,然后使用递归 cte 将当前月份的交易与当时更新的余额进行交易。 我知道这也可以通过表更新来完成,但我正在寻找递归。
表结构如下:
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 和 sum 窗口函数,但它并没有提供连续平衡,只是逐行平衡。
同样在 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
或
;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
-
SQL Server 2008
标签: sql sql-server recursion common-table-expression recursive-query