【发布时间】:2016-10-06 19:56:12
【问题描述】:
我坐在两张桌子旁(虽然它们是临时表),看起来像这样:
CREATE TABLE [dbo].[Invoice]
(
[InvoiceId] [int] NOT NULL,
[ReceiverId] [int] NOT NULL,
[Amount] [numeric](19, 2) NOT NULL,
[Priority] [int] NOT NULL
);
GO
CREATE TABLE [dbo].[Payment]
(
[PaymentId] [int] NOT NULL,
[SenderId] [int] NOT NULL,
[Amount] [numeric](19, 2) NOT NULL
);
GO
数据可能如下所示:
发票
InvoiceId ReceiverId Amount Priority
1 1 100.00 1
2 1 100.00 2
3 2 100.00 1
4 2 100.00 2
5 1 200.00 3
付款
PaymentId SenderId Amount
1 1 50.00
2 1 45.00
3 2 95.00
4 2 105.00
收款存储在Payment。我的代码的任务是在发件人的发票之间分配Payment.Amount。
两者之间的关系键是ReceiverId和SenderId。
Priority 列对于 ReceiverId 来说是唯一的,并且值“1”的优先级高于“2”。
带有SenderId“1”的Payment 行可以用于无限数量的带有ReceiverId“1”的发票 - 如果Payment.Amount 列中没有足够的所有发票,他们将按照他们的Priority支付。
我正在想办法在不使用循环或光标的情况下对其进行编程。有什么建议么? (我坐在 SQL Server 2014 上)。
我的预期输出是:
1) Payment 1 and 2 would be used to partially pay Invoice 1.
2) Payment 3 would be used to partially pay Invoice 3.
3) Payment 4 would then complete invoice 3.
4) Payment 4 would then completely pay invoice 4.
5) Invoice 2 and 5 would be left completely unpaid.
【问题讨论】:
-
在等待答案时,您可能需要仔细阅读this 问题。
-
SQL Server 2014,将其添加到问题中。
-
仅使用您的样本数据,您的预期结果应该是什么?
-
我希望这样:1) 付款 1 和 2 将用于部分支付发票 1。2) 付款 3 将用于部分支付发票 3。3) 然后付款 4 将完成发票 3。4) 付款 4 将完全支付发票 4。5) 发票 2 和 5 将完全未支付。
-
将此添加到问题中,因为换行符在评论中不起作用...
标签: sql sql-server tsql sql-server-2014