I implemented the solution in a recursive CTE :
;with TranGroup as ( select TransactionID , InvoiceID as NextInvoice , TransactionID as RelatedTransaction , cast(TransactionID as varchar(8000)) as TransactionChain from TransactionInvoiceMap union all select g.TransactionID , m1.InvoiceID , m.TransactionID , g.TransactionChain + ',' + cast(m.TransactionID as varchar(11)) from TranGroup g join TransactionInvoiceMap m on g.NextInvoice = m.InvoiceID join TransactionInvoiceMap m1 on m.TransactionID = m1.TransactionID where ',' + g.TransactionChain + ',' not like '%,' + cast(m.TransactionID as varchar(11)) + ',%' ) , RelatedTrans as ( select distinct TransactionID, RelatedTransaction from TranGroup ) , RelatedInv as ( select distinct TransactionID, NextInvoice as RelatedInvoice from TranGroup ) select TransactionID , ( select sum(Amount) from Transactions where TransactionID in ( select RelatedTransaction from RelatedTrans where TransactionID = t.TransactionID ) ) as TotalAsscTransactions , ( select sum(Amount) from Invoices where InvoiceID in ( select RelatedInvoice from RelatedInv where TransactionID = t.TransactionID ) ) as TotalAsscInvoiced from Transactions t
There is probably a place for optimization (including naming objects on my part!), But I believe that I have at least the right solution, which will collect all the possible transaction-account relationships for inclusion in the calculations.
I was not able to get the existing solutions on this page to give the desired OP result, and they became uglier when I added more test data. I am not sure if the OP has posted a โslowโ solution as indicated. It is very possible that I misinterpreted the question.
Additional Information:
I often saw that recursive queries can be slow when working with large datasets. Perhaps this may be the subject of another question. In this case, all that needs to be tried on the SQL side may be to limit the range (add where
clauses), index the base tables, first select the CTE in the temp table, index this temporary table, and think about the best stop state for the CTE. .. but profile first, of course.
source share