我有一张发票表,如下所示:
InvoiceDate InvoiceNumber PaidDate PayStatus Amount
-----------------------------------------------------------
2012-1-23 1234 2012-02-28 Unpaid 1234
2012-2-01 2345 2012-03-12 Paid 23456
我需要通过(及其每月的总和)来确定条件。
我只为当月创造了一个WHERE CLAUSE。逻辑是这样的。
仅适用于当月(报告上个月的最后一天)。我不知道如何在发票表中的所有月份这样做。
-- only extract invoices with invoice dates less than or equal to the last day of the previous month
AND b.InvoiceDt <= DATEADD(dd, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
-- the 'lateness' should not exceed 90 days (lateness = diff(Period - (InvoiceDt + Terms)))
AND DATEDIFF(day, DATEADD(day, ISNULL(b.Term, 0), b.InvoiceDt), DATEADD(dd, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))) <= 90
-- take either unpaid PayStatus OR if it's marked as paid, ActualPaymentdt should be greater than or equal to the last day of the previous month
AND (b.PayStatus = 'Unpaid' OR b.ActualPaymentDt >= DATEADD(dd, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)))
-- if the day component of invoice date equals 1 AND it belongs to acct 4300, exclude it
AND NOT (b.AccountNumber = 4300 AND DAY(b.InvoiceDt) = 1)
答案 0 :(得分:1)
加入另一个包含invoices
表中所有月份的派生表:
CROSS JOIN (SELECT DISTINCT DATEADD(MONTH, DATEDIFF(MONTH, 0, InvoiceDt), 0) as InvoiceMonth
FROM invoices) m
然后将GETDATE()
替换为m.InvoiceMonth
。
并且不要忘记GROUP BY m.InvoiceMonth
。