我在发票和信用卡交易之间存在多对多关系,我试图将它们的总和映射在一起。思考这个问题的最好方法是将 TransactionInvoiceMap 想象成一个二分图。对于每个连接的子图,找到该子图中所有发票的总数和所有交易的总数。在我的查询中,我想返回为每个子图计算的值以及它们关联的事务 ID。关联交易的合计应相同。
更明确地说,给定以下交易/发票
Table: TransactionInvoiceMap
TransactionID InvoiceID
1 1
2 2
3 2
3 3
Table: Transactions
TransactionID Amount
1 $100
2 $75
3 $75
Table: Invoices
InvoiceID Amount
1 $100
2 $100
3 $50
我想要的输出是
TransactionID TotalAsscTransactions TotalAsscInvoiced
1 $100 $100
2 $150 $150
3 $150 $150
请注意,发票 2 和 3 以及交易记录 2 和 3 是逻辑组的一部分。
这是一个显然有效但速度很慢的解决方案(简化,名称已更改)。我很难弄清楚如何优化它,但我认为这将涉及消除 TransactionInvoiceGrouping 中的子查询。随意提出一些完全不同的建议。
with TransactionInvoiceGrouping as (
select
-- Need an identifier for each logical group of transactions/invoices, use
-- one of the transaction ids for this.
m.TransactionID,
m.InvoiceID,
min(m.TransactionID) over (partition by m.InvoiceID) as GroupingID
from TransactionInvoiceMap m
)
select distinct
g.TransactionID,
istat.InvoiceSum as TotalAsscInvoiced,
tstat.TransactionSum as TotalAsscTransactions
from TransactionInvoiceGrouping g
cross apply (
select sum(ii.Amount) as InvoiceSum
from (select distinct InvoiceID, GroupingID from TransactionInvoiceGrouping) ig
inner join Invoices ii on ig.InvoiceID = ii.InvoiceID
where ig.GroupingID = g.GroupingID
) as istat
cross apply (
select sum(it.Amount) as TransactionSum
from (select distinct TransactionID, GroupingID from TransactionInvoiceGrouping) ig
left join Transactions it on ig.TransactionID = it.TransactionID
where ig.GroupingID = g.GroupingID
having sum(it.Amount) > 0
) as tstat