我正在实施会计软件。
在计算分层自引用主题的资产负债表时,请告诉我最快的算法
这些是我的表格:
主题表:
TopicID nvarchar(50) -- is Parent Field
ParentID nvarchar(50) -- is Child Field
Description nvarchar(512)
------------DocumentDetal table
DocumentNumber nvarchar(50)
TopicFK nvarchar(50)
Debit decimal(18,0)
Credit decimal(18,0)
两个表与TopicID
和TopicFK
列相关,请告诉我如何使用SQL存储过程计算资产负债表。
关注的是数据样本:
以下是文件:
其实我想要跟随计算结果:
答案 0 :(得分:2)
对于SQL Server 2008 R2
,此处适用于sumDebit and sumCredit
。不了解如何计算Res Debit and Res credit
,但我认为您也可以修改以获得Res value
。
无论如何,这是CTE
感谢Recursive sum in tree structure中的Mikael Eriksson
with T as
(
select t.TopicID, t.ParentID, sum(d.Debit) as sumDebit, sum(d.Credit) as sumCredit
from Topics t
left join DocumentDetail d
on t.TopicID = d.TopicFK
group by t.TopicID, t.ParentID
)
,C as
(
select T.TopicID,
T.sumDebit,
T.sumCredit,
T.TopicID as RootID
from T
union all
select T.TopicID,
T.sumDebit,
T.sumCredit,
C.RootID
from T
inner join C
on T.ParentId = C.TopicID
)
select T.TopicID,
T.ParentId,
S.sumDebitIncludingChildren sumDebit,
S.sumCreditIncludingChildren sumCredit
from T
inner join (
select RootID,
sum(sumDebit) as sumDebitIncludingChildren,
sum(sumCredit) as sumCreditIncludingChildren
from C
group by RootID
) as S
on T.TopicID = S.RootID
order by T.TopicID
option (maxrecursion 0);
中测试好了