应收帐款表的收款天数

时间:2017-01-09 18:02:31

标签: sql sql-server

我有一个带

的AR表
Client ID: Client number
InvoiceNumber: Number of invoice
ARtype: 1=Invoice, 4=Payment and few more variables. I am only interested in mentioned ones.
Posting Date: Date time of transaction. 

我想运行一个查询,以显示从表格中发出发票时收取付款所需的天数。我使用了以下查询,但无法使用datediff函数中的条件。

Select InvoiceNumber, datediff(d,Min(postingdate),Max(postingdate)) as Days

from AR

group by InvoiceNumber


Adjustment: sample data
arcltid  ARCltNum     ARType      ARDate        ARAmt      ARApplyto
8144        DDC         1       08/31/2016 0:00  5900       115908
8144        DDC         1       05/31/2016 0:00    0        114014
8145        DDC         1        04/30/2016 0:00    0       113584
8144        DDC         1       04/30/2016 0:00   1600      113583
8144        DDC         1       04/04/2016 0:00    0        110163
8144        DDC         1       02/29/2016 0:00   2200      109790
8144        DDC         4       09/27/2016 0:00   -1950     110163
8144        DDC         4       10/17/2016 0:00   -2500     114014
8144        DDC         4       10/17/2016 0:00   -2800      115908

我只专注于1和4.

2 个答案:

答案 0 :(得分:0)

您可以使用CASE:

select
    InvoiceNumber,
    datediff(
        d,
        min(case when ARType = 1 then postingDate end),
        max(case when ARType = 4 then postingDate end)
    ) days
from AR
group by InvoiceNumber;

答案 1 :(得分:0)

你想要更接近这个:

SELECT invoice.InvoiceNumber, datediff(d, invoice.postingDate, payment.postingDate) as Days
  FROM (SELECT * FROM AR WHERE ARtype = 1) invoice
  LEFT JOIN (SELECT * FROM AR WHERE ARtype = 4) payment
         ON invoice.ClientID = payment.ClientID
        AND invoice.invoiceNumber = payment.invoiceNumber