I have this data in a table:
service | vat | ini_date | end_date
1 A 10/01/2017 31/01/2017
2 A 15/01/2017 28/02/2017
3 A 15/02/2017 31/03/2017
4 B 15/01/2017 31/03/2017
5 B 15/02/2017 31/03/2017
6 B 20/04/2017 31/05/2017
7 B 20/05/2017 31/05/2017
And I have to group by VAT services which have match in time.
My output should by this:
group service | vat | ini_date | end_date
1 1 A 10/01/2017 31/01/2017
1 2 A 15/01/2017 28/02/2017
1 3 A 15/02/2017 31/03/2017
1 4 B 15/01/2017 31/03/2017
1 5 B 15/02/2017 31/03/2017
2 6 B 20/04/2017 31/05/2017
2 7 B 20/05/2017 31/05/2017
I can't use procedures, I'm trying with some analytical function but there is a lot of casuistics. The problem starts when you have more than three services that coincide in time individually.
Any idea is welcome. Thanks
It seems you incrementing for each "block" of time, so one has to detect a "gap" in the dates. Below I have used a Postgres fiddle using window functions
LEAD()to discover if there is a gap which is then arranged into the final output usingDENSE_RANK(). In the secondcte"common_dates" a correlated subquery is used to locate a date when the next gap has been detected. This information is then used to order the finalDENSE_RANK(). There may be a more efficient method in Teradata to execute this subquery but I'm not able to trial that).NB: I have assumed "service" can be used for ordering in the
LEAD()function and in the correlated subquery.Notes: "group" isn't something I would recommend as a column name so I used "group_num" instead and I extended the sample data for testing the query against.
Demo (PostgreSQL 9.6)
Query 1:
Results: