PaymentID Date TotalBill Bill Paid Amount Remaining Bill
1 05-04-2018 2,10,000 20,000 1,90,000
2 10-05-2018 2,10,000 60,000 1,30,000
3 13-06-2018 2,10,000 30,000 1,00,000
如上所述,帐单的付款是在不同的日期分期付款的。每次支付部分账单时如何查找剩余的账单金额?我想要上面的结果,但是我不知道正确的SQL Server查询。
我使用了以下查询:
SELECT siph.SupplyPaymentID,si.SupplyInvoiceID,siph.DateOfPayment,si.TotalBill,siph.BillPaidAmount,(si.TotalBill-siph.BillPaidAmount) as RemainingBillAmount from SupplyInvoicePaymentHistory siph inner join SupplyInvoice si on siph.SupplyInvoiceID=si.SupplyInvoiceID
但是会产生以下错误结果
PaymentID Date TotalBill Bill Paid Amount Remaining Bill
1 05-04-2018 2,10,000 20,000 1,90,000
2 10-05-2018 2,10,000 60,000 1,50,000
3 13-06-2018 2,10,000 30,000 1,80,000
如何在每次支付部分账单时找到正确的剩余账单金额?
答案 0 :(得分:0)
将df <- structure(list(ID = c(101, 102, 103, 104, 105, 106, 107), Adm = structure(c(1326309720,
1326309900, 1328990700, 1328997240, 1329000840, 1329004440, 1329004680
), class = c("POSIXct", "POSIXt"), tzone = ""), Disc = structure(c(1326313800,
1326317340, 1328995860, 1329003060, 1329006660, 1329013860, 1329013860
), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("ID",
"Adm", "Disc"), row.names = c(NA, -7L), class = "data.frame")
# ID Adm Disc
#1 101 2012-01-12 00:52:00 2012-01-12 02:00:00
#2 102 2012-01-12 00:55:00 2012-01-12 02:59:00
#3 103 2012-02-12 01:35:00 2012-02-12 03:01:00
#4 104 2012-02-12 03:24:00 2012-02-12 05:01:00
#5 105 2012-02-12 04:24:00 2012-02-12 06:01:00
#6 106 2012-02-12 05:24:00 2012-02-12 08:01:00
#7 107 2012-02-12 05:28:00 2012-02-12 08:01:00
函数与SUM
子句一起使用。
OVER
答案 1 :(得分:0)
您可以尝试如下查询
SELECT
siph.SupplyPaymentID,
si.SupplyInvoiceID,
siph.DateOfPayment,
si.TotalBill,
siph.BillPaidAmount,
si.TotalBill-SUM(siph.BillPaidAmount) over( order by siph.DateOfPayment asc) as RemainingBillAmount
from SupplyInvoicePaymentHistory siph
inner join SupplyInvoice si
on siph.SupplyInvoiceID=si.SupplyInvoiceID
答案 2 :(得分:0)
尝试一下
;WITH CTE(PaymentID,[Date],TotalBill,BillPaidAmount)
AS
(
SELECT 1,'05-04-2018',210000,20000 UNION ALL
SELECT 2,'10-05-2018',210000,60000 UNION ALL
SELECT 3,'13-06-2018',210000,30000
)
SELECT *, TotalBill-SUM(BillPaidAmount)OVER(ORDER BY [Date]) AS RemainingBill FROM CTE
结果
PaymentID Date TotalBill BillPaidAmount RemainingBill
-----------------------------------------------------------------
1 05-04-2018 210000 20000 190000
2 10-05-2018 210000 60000 130000
3 13-06-2018 210000 30000 100000
答案 3 :(得分:0)
如果我使用siph.DateOfPayment而不是“ OVER(ORDER BY日期行在未绑定前导和当前行之间)的日期”中的日期,则会产生以下结果
PaymentID Date TotalBill Bill Paid Amount Remaining Bill
1 05-04-2018 2,10,000 20,000 1,90,000
2 10-05-2018 2,10,000 60,000 3,40,000
3 13-06-2018 2,10,000 30,000 3,40,000