计算"首先逾期"付款时间表的日期

时间:2015-12-09 15:15:42

标签: sql-server sql-server-2014

摘要

我正在写一个" Aged debtors"根据收到的发票和付款表查看,个别付款到期付款与收到付款之间没有关联。如何使用SQL计算未结算和最早的未结算发票金额?

示例

发票

+------------+-----------+------------+
| CustomerID | AmountDue |  DateDue   |
+------------+-----------+------------+
|          1 |       100 | 2015-02-01 |
|          1 |       100 | 2015-03-01 |
|          1 |       100 | 2015-04-01 |
+------------+-----------+------------+

收到付款

+------------+----------------+--------------+
| CustomerID | AmountReceived | DateReceived |
+------------+----------------+--------------+
|          1 |             60 | 2015-01-11   |
|          1 |            100 | 2015-02-21   |
+------------+----------------+--------------+

所需输出(在2015-04-01之后的某个时间运行)

+------------+-------------------+-----------------------+
| CustomerID | AmountOutstanding | FirstUnsettledInvoice |
+------------+-------------------+-----------------------+
|          1 |               140 | 2015-03-01            |
+------------+-------------------+-----------------------+

当前输出

+------------+-------------------+-----------------------+
| CustomerID | AmountOutstanding | FirstUnsettledInvoice |
+------------+-------------------+-----------------------+
|          1 |               140 | 2015-04-01            |
+------------+-------------------+-----------------------+

当前查询

  SELECT TotalPayment.CustomerID, TotalDue - TotalReceived as AmountOutstanding, MaxDueDate as FirstUnsettledInvoice
  FROM 
    (SELECT CustomerID, SUM(AmountReceived) as TotalReceived
    FROM PaymentReceived
    GROUP BY CustomerID) as TotalPayment
  JOIN
    (SELECT CustomerID, SUM(AmountDue) as TotalDue, MAX(DateDue) as MaxDueDate
    FROM Invoice
    WHERE DateDue < GETUTCDATE()
    GROUP BY CustomerID) as TotalInvoice
  ON TotalPayment.CustomerID = TotalInvoice.CustomerID

1 个答案:

答案 0 :(得分:0)

感谢Tab Alleman的评论,我写了以下查询,给出了我追求的结果:

 SELECT CustomerID, MAX(runningtotal) - MAX(TotalReceived), MIN(DateDue) FROM (
      SELECT 
        TotalPayment.CustomerID,
        TotalReceived,
        AmountDue,
        sum(AmountDue) over(order by DateDue rows unbounded preceding) as runningtotal,
        DateDue
      FROM
        Invoice
      JOIN
        (SELECT CustomerID, SUM(AmountReceived) as TotalReceived
        FROM PaymentReceived
        GROUP BY CustomerID) as TotalPayment
      ON TotalPayment.CustomerID = Invoice.CustomerID
) AS subquery
 WHERE subquery.AmountDue < subquery.runningtotal
 Group By CustomerID