0

我有一张如下所示的发票表:

InvoiceDate InvoiceNumber   PaidDate    PayStatus   Amount
-----------------------------------------------------------
2012-1-23   1234            2012-02-28  Unpaid      1234
2012-2-01   2345            2012-03-12  Paid        23456

我需要根据条件对这些进行分组(并取他们每月的总和)。

我想出了一个仅针对当前月份的 WHERE 条款。逻辑是这样的。

  • 仅提取发票日期小于或等于上个月最后一天的发票
  • “迟到”不应超过 90 天(迟到 = diff(Period - (InvoiceDt + Terms)))
  • 取 unpaid PayStatus 或者如果它被标记为已付款,ActualPaymentdt 应该大于或等于上个月的最后一天
  • 如果发票日期的日期部分等于 1 并且属于帐户 4300,则排除它

这仅适用于当前月份(报告上个月的最后一天)。我不知道如何在发票表中为 ALL MONTHS 执行此操作。

    -- 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)
4

1 回答 1

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

于 2012-11-21T22:11:45.063 回答