I want to display data based on start date and end date. a code can contain different dates. if any time intervel is continues then I need to merge that rows and display as single row
Here is sample data
Code Start_Date End_Date Volume
470 24-Oct-10 30-Oct-10 28
470 17-Oct-10 23-Oct-10 2
470 26-Sep-10 2-Oct-10 2
471 22-Aug-10 29-Aug-10 2
471 15-Aug-10 21-Aug-10 2
The output result I want is
Code Start_Date End_Date Volume
470 17-Oct-10 30-Oct-10 30
470 26-Sep-10 2-Oct-10 2
471 15-Aug-10 29-Aug-10 4
a code can have any no. of time intervels. Pls help. Thank you
Based on your sample data (which I’ve put in a table called Test), and assuming no overlaps:
Explanation:
The Ranges CTE contains all rows from the original table (because some of them might be relevant) and all rows we can form by joining ranges together (both original ranges, and any intermediate ranges we construct – we’re doing recursion here).
Then ExtendedRanges (poorly named) finds, for any particular End_Date, the earliest Start_Date that can reach it.
Finally, we query this second CTE, to find, for any particular Start_Date, the latest End_Date that is associated with it.
These two queries combine to basically filter the Ranges CTE down to “the widest possible Start_Date/End_Date pair” in each set of overlapping date ranges.
Sample data setup: