Skip to content
Advertisement

SQL Server – Counting total number of days user had active contracts

I want to count the number of days while user had active contract based on table with start and end dates for each service contract. I want to count the time of any activity, no matter if the customer had 1 or 5 contracts active at same time.

In result I want a table:

Where

1477 stands by 1053 (days from 13.02.2017 to 02.01.2020 – user had active contracts during this time) + 424 (days from 18.02.2021 to 18.04.2022)

832 stands by 529 (days from 19.01.2019 to 01.07.2020) + 303 (days from 19.06.2021 to 18.04.2022).

I tried some queries with joins, datediff’s, case when conditions but nothing worked. I’ll be grateful for any help.

Advertisement

Answer

If you don’t have a Tally/Numbers table (highly recommended), you can use an ad-hoc tally/numbers table

Example or dbFiddle

Results

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