次のような請求書の表があります。
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 に等しく、それが会計 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)