Skip to content
Advertisement

Consolidate information (time serie) from two tables

MS SQL Server

I have two tables with different accounts from the same customer:

Table1:

ID ACCOUNT FROM TO
1 A 01.10.2019 01.12.2019
1 A 01.02.2020 09.09.9999

and table2:

ID ACCOUNT FROM TO
1 B 01.12.2019 01.01.2020

As result I want a table that summarize the story of this costumer and shows when he had an active account and when he doesn’t.

Result:

ID FROM TO ACTIV Y/N
1 01.10.2019 01.01.2020 Y
1 02.01.2020 31.01.2020 N
1 01.02.2020 09.09.9999 Y

Can someone help me with some ideas how to proceed?

Advertisement

Answer

This is the typical gaps and island problem, and it’s not usually easy to solve.

You can achieve your goal using this query, I will explain it a little bit.

You can test on this db<>fiddle.

First of all… I have unified your two tables into one to simplify the query.

You can then get your gaps and island using, for example, a query like this. It combines recursive cte to generate a calendar (cte_cal) and lag and lead operations to get the previous/next record information to build the gaps.

Dates like '9999-09-09' must be treated like exceptions, otherwise I would have to create a calendar until that date, so the query would take long time to resolve.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement