根据SQL中的条件对发票进行月份分组

时间:2012-11-21 21:59:28

标签: sql sql-server-2008 tsql

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

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。逻辑是这样的。

  • 仅提取发票日期小于或等于上个月最后一天的发票
  • '迟到'不应超过90天(迟到=差异(期间 - (InvoiceDt +条款)))
  • 采取未支付的PayStatus或者如果它被标记为已付款,则ActualPaymentdt应该大于或等于上个月的最后一天
  • 如果发票日期的日期部分等于1并且它属于acct 4300,则将其排除

仅适用于当月(报告上个月的最后一天)。我不知道如何在发票表中的所有月份这样做。

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

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