样本数据
使用 ISO 日期格式以避免任何混淆。
docdate
和列将isdebit
不会在解决方案中使用...
- 我忽略了
docdate
假设值是递增的,并且允许在任何借记费之前存入贷记费。
isdebit
如果您无论如何要将借记和贷记交易存储在单独的表中,则该标志似乎是多余的。
更新的样本数据:
create table debit
(
personid int,
docdate date,
docid int,
fee int,
isdebit bit
);
insert into debit (personid, docdate, docid, fee, isdebit) values
(88, '2021-02-14', 1, 5, 1),
(88, '2021-02-15', 2, 5, 1);
create table credit
(
personid int,
docdate date,
docid int,
fee int,
isdebit bit
);
insert into credit (personid, docdate, docid, fee, isdebit) values
(88, '2021-02-16', 3, 3, 0),
(88, '2021-02-17', 4, 7, 0);
解决方案
这里有几个步骤:
- 构建借方费用的滚动总和。使用第一个公用表表达式 (
cte_debit
) 完成。
- 为信贷费用构建一个滚动总和。使用第二个公用表表达式 (
cte_credit
) 完成。
- 获取所有借记信息 (
select * from cte_debit
)
- 查找适用于当前借记信息的第一个贷记信息。用第一个
cross apply
( cc1
) 完成。这包含docid
适用于借方凭证的第一个凭证。
- 查找适用于当前借记信息的最后一个贷记信息。用第二个
cross apply
( cc2
) 完成。这包含docid
适用于借记凭证的最后一个凭证的编号。
- 通过选择第一个和最后一个适用单据 ( )之间的所有单据,查找适用于当前借记信息的所有贷记信息。
join cte_credit cc on cc.docid >= cc1.docid and cc.docid <= cc2.docid
- 结合滚动总和数字来计算剩余的信用费用 (
cc.credit_sum - cd.debit_sum
)。使用case
表达式过滤掉负值。
完整解决方案:
with cte_debit as
(
select d.personid,
d.docid,
d.fee,
sum(d.fee) over(order by d.docid rows between unbounded preceding and current row) as debit_sum
from debit d
),
cte_credit as
(
select c.personid,
c.docid,
c.fee,
sum(c.fee) over(order by c.docid rows between unbounded preceding and current row) as credit_sum
from credit c
)
select cd.personid,
cd.docid as deb_docid,
cd.fee as deb_fee,
cc.docid as cre_docid,
cc.fee as cre_fee,
case
when cc.credit_sum - cd.debit_sum >= 0
then cc.credit_sum - cd.debit_sum
else 0
end as cre_fee_remaining
from cte_debit cd
cross apply ( select top 1 cc1.docid, cc1.credit_sum
from cte_credit cc1
where cc1.personid = cd.personid
and cc1.credit_sum <= cd.debit_sum
order by cc1.credit_sum desc ) cc1
cross apply ( select top 1 cc2.docid, cc2.credit_sum
from cte_credit cc2
where cc2.personid = cd.personid
and cc2.credit_sum >= cd.debit_sum
order by cc2.credit_sum desc ) cc2
join cte_credit cc
on cc.personid = cd.personid
and cc.docid >= cc1.docid
and cc.docid <= cc2.docid
order by cd.personid,
cd.docid,
cc.docid;
结果
personid deb_docid deb_fee cre_docid cre_fee cre_fee_remaining
-------- --------- ------- --------- ------- -----------------
88 1 5 3 3 0
88 1 5 4 7 5
88 2 5 4 7 0
小提琴以查看实际情况。这还包含中间 CTE 结果和一些可以取消注释的注释帮助列,以帮助进一步理解解决方案。