计算每个客户当前发票后 6 个月内创建的发票 - SQL 服务器

Count invoices created in next 6 Months after current invoice for each customer - SQL Server

我有一个数据集,我需要在其中计算未来 6 个月内创建的发票,创建的发票包括同一天创建的任何其他发票。这是一些示例数据:

Customer Invoice Date Expected Ans
1 A 1/1/2021 2
1 B 3/1/2021 3
1 C 5/1/2021 3
1 D 8/1/2021 2
1 E 8/1/2021 2
1 F 10/1/2021 0
2 Z 1/1/2021 2
2 Y 5/1/2021 3
2 X 5/1/2021 3
2 W 10/1/2021 1
2 V 10/1/2021 1

您似乎想计算每个客户在接下来的 6 个月内发生的行数。使用该逻辑,我得到了您预期的结果。

计算每个客户 6 个月内的未来发票

DROP TABLE IF EXISTS #Invoice 

CREATE TABLE #Invoice
(
    Customer INT
    ,Invoice CHAR(1)
    ,InvoiceDate DATE
)

INSERT INTO #Invoice
VALUES
(1,'A','2021-01-01')
,(1,'B','2021-03-01')
,(1,'C','2021-05-01')
,(1,'D','2021-08-01')
,(1,'E','2021-08-01')
,(1,'F','2021-10-01')
,(2,'Z','2021-01-01')
,(2,'Y','2021-05-01')
,(2,'X','2021-05-01')
,(2,'W','2021-10-01')
,(2,'V','2021-10-01')


SELECT *
FROM #Invoice AS A
OUTER APPLY (
    SELECT COUNT(*) AS InvoiceCnt
    FROM #Invoice AS DTA
    WHERE A.Customer = DTA.Customer /*Match on same customer*/
    AND A.Invoice <> DTA.Invoice /*Don't join row to self*/
    AND A.InvoiceDate BETWEEN DATEADD(mm,-6,DTA.InvoiceDate) AND DTA.InvoiceDate /*Look for invoices within 6 months*/
) AS B