I am using iReport 3.0.0, PostgreSQL 9.1. For a report I need to compare date ranges from invoices with date ranges in filters and print for every invoice code if a filter range is covered, partially covered, etc. To complicate things, there can be multiple date ranges per invoice code.
Table Invoices
ID Code StartDate EndDate
1 111 1.5.2012 31.5.2012
2 111 1.7.2012 20.7.2012
3 111 25.7.2012 31.7.2012
4 222 1.4.2012 15.4.2012
5 222 18.4.2012 30.4.2012
Examples
Filter: 1.5.2012. - 5.6.2012.
Result that I need to get is:
code 111 - partialy covered
code 222 - invoice missing
Filter: 1.5.2012. - 31.5.2012.
code 111 - fully covered
code 222 - invoice missing
Filter: 1.6.2012. - 30.6.2012.
code 111 - invoice missing
code 222 - invoice missing
After clarification in comment.
Your task as I understand it:
Check for all supplied individual date ranges (
filter
) whether they are are covered by the combined date ranges of sets of codes in your table (invoice
).It can be done with plain SQL, but it is not a trivial task. The steps could be:
Supply date ranges as filters.
Combine date ranges in
invoice
table per code. Can result in one or more ranges per code.Look for overlaps between filters and combined invoices
Classify: fully covered / partially covered. Can result in one full coverage, one or two partial coverages or no coverage. Reduce to maximum level of coverage.
Display one row for every combination of (filter, code) with the resulting coverage, in a sensible sort order
Ad hoc filter ranges
Or put them in a (temporary) table and use the table instead.
Combine overlapping / adjacent date ranges per code
Alternative final SELECT (may be faster or not, you'll have to test):
Combine to one query
Tested and works for me on PostgreSQL 9.1.