在sql中优先与债权人分享现金

问题描述 投票:2回答:2

我在sql 2014中有一个名为“tblPaymentPlan”的表,如下所示:

Creditors    PlanToPay      َAmount
----------------------------------
A            2017-01-20     2000
A            2017-02-20     1500
A            2017-03-20     3000
B            2017-01-25     3000
B            2017-02-25     1000

以及另一个名为“tblPaid”的表如下:

Creditors    Paid      َ
-----------------
A            4500
B            3500

以及我期望的结果:

Creditors    PlanToPay      َRemain
----------------------------------
A            2017-01-20     0
A            2017-02-20     0
A            2017-03-20     2000
B            2017-01-25     0
B            2017-02-25     500

我根本不知道做这份工作!你能不能帮我完成这份工作。请告知我的表格中有很多记录。我需要这个查询预算计划。 (我们可以使用数字来定义优先级而不是日期)

sql sql-server sql-server-2014
2个回答
1
投票

您可以从付费表格中的金额中减去运行总额,如果小于0,则将剩余设置为0,否则金额与运行总计的差异。

select pp.creditors,pp.plantopay,
case when sum(pp.amount) over(partition by pp.creditors order by pp.plantopay)-coalesce(pd.paid,0) <= 0 then 0
else sum(pp.amount) over(partition by pp.creditors order by pp.plantopay)-coalesce(pd.paid,0) end as remain
from tblpaymentplan pp
left join tblPaid pd on pp.creditors=pd.creditors

3
投票

你想要的是一个总计的欠款,你可以从中减去所支付的金额。

SELECT Creditors, PlanToPay, IIF(ABS(Remain)!=Remain,0,IIF(Remain<Amount,Remain,Amount)) as Remain
FROM (SELECT pp.Creditors, pp.PlanToPay, pp.Amount,
  SUM(pp.Amount) OVER(PARTITION BY pp.Creditors ORDER BY pp.PlanToPay ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)-tp.paid AS Remain
  FROM tblPaymentPlan pp 
  JOIN (SELECT creditors, sum(paid) as paid from tblpaid group by creditors) tp
  ON pp.creditors = tp.creditors) ss
ORDER By Creditors, PlanToPay

SQLFiddle

在窗口函数(SUM OVER)中,PARTITION将债权人分开,ORDER确定行的排列方式(按日期),ROWS子句告诉它在此行之前使用分区中的所有行并在运行中包含此行总。然后,我们从该运行总计中减去支付给该债权人的所有东西的总和。

这当然给了我们很多负数,所以我们在子查询中做到了。主查询检查剩余的绝对值是否等于值,如果是正数则为true,否则为false,如果为true则返回值,如果不是则返回0,否则返回0。

更新 - 添加了多行的处理,但仍有欠值

© www.soinside.com 2019 - 2024. All rights reserved.