On a weekly basis, I need to understand how many invoices are in the system. I've made a couple of attempts at this and none of them have generated what I'm after. Every week we get invoices in. Some invoices carry over into other weeks, some invoices age out of the system.
I've put together a table of unique weeks. There is NO tie between individual weeks and invoices other than some dates in the invoice table. I have access to three:
created - date invoice loaded into system
paid_date - date invoice was paid.
due_date - date the invoice is due.
The business rules are
Group all available invoices per week. An invoice is no longer available if it has been paid or if it has gone past its due date without being paid. Below are some sample records. I need help writing the where clause that gets rid of unavailable invoices.
CREATE TABLE #weeks(
weeks_id INT IDENTITY(1,1),
week_of_year_begin_date DATE,
week_of_year_end_date DATE,
CONSTRAINT [PK_weeks_id] PRIMARY KEY CLUSTERED ([weeks_id] ASC)
)
INSERT INTO #weeks(week_of_year_begin_date, week_of_year_end_date)
SELECT '2014-02-02','2014-02-08'
UNION ALL
SELECT '2014-02-09','2014-02-15'
UNION ALL
SELECT '2014-02-16','2014-02-22'
UNION ALL
SELECT '2014-02-23','2014-03-01'
CREATE TABLE #invoices(
invoice_id INT IDENTITY(1,1),
created DATE,
paid_date DATE,
due_date DATE
CONSTRAINT [PK_invoice_id] PRIMARY KEY CLUSTERED ([invoice_id] ASC)
)
INSERT INTO #invoices(created,due_date,paid_date)
SELECT '2014-2-01','2014-02-20','2014-02-19'
UNION ALL
SELECT '2014-2-01','2014-02-10', NULL
UNION ALL
SELECT '2014-2-01','2014-02-17','2014-02-16'
UNION ALL
SELECT '2014-2-01','2014-03-03',NULL
UNION ALL
SELECT '2014-2-01','2014-02-15',NULL
UNION ALL
SELECT '2014-2-01','2014-02-28','2014-02-12'
UNION ALL
SELECT '2014-2-01','2014-03-07','2014-02-19'
UNION ALL
SELECT '2014-2-01','2014-02-21','2014-02-14'
UNION ALL
SELECT '2014-2-01','2014-03-14','2014-02-11'
UNION ALL
SELECT '2014-2-01','2014-02-17','2014-02-17'
SELECT
w.weeks_id,
w.week_of_year_end_date,
i.due_date,
i.paid_date
FROM #weeks w
CROSS JOIN #invoices i
DROP TABLE #invoices
DROP TABLE #weeks