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(期間 - (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)
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 に答える