2012-11-21 27 views
0

我有發票的表看起來像這樣:月分組,根據具體的情況在SQL

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(週期 - (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

加入對包含在invoices表中的所有月份另一個派生表:

CROSS JOIN (SELECT DISTINCT DATEADD(MONTH, DATEDIFF(MONTH, 0, InvoiceDt), 0) as InvoiceMonth 
      FROM invoices) m 

然後用m.InvoiceMonth替代GETDATE()

而且不要忘了GROUP BY m.InvoiceMonth爲好。

+0

我可以吻你。非常感謝!!! – Kyle