Z
Z
zhaar2019-09-04 13:09:21
SQL Server
zhaar, 2019-09-04 13:09:21

How to track period break in dates?

So, let's say there is some parameter [ddd] (in fact there are many of them), which has several rows in the table with its validity period:
name - startdate - enddate
[ddd] - 20190101 - 20190501
[ddd] - 20190502 - 20190607
[ ddd] - 20190610 - 29991231
The data shows that there is a gap between the second and third row - the action ends on June 7th and continues only on 10th (ie, 8th and 9th numbers fell out). In the example, this is one, but in fact there may be more such intervals on the period.
I thought to count by the number of days in order to find at least those records for which they do not coincide with the start date of the month, but I realized that this is not an option, because. parameters may not start on January 1st and end before the current date.
How can this interval be found through a query in MSSQL?
PS: it is possible to use the following server versions MSSQL Server Enterprise 2014 and Standard 2016

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2019-09-04
@zhaar

SELECT period.name, period.startdate
FROM period 
  LEFT OUTER JOIN period AS period_end ON period.name = period_end.name 
    AND DATEADD(dd, 1, period.enddate) = period_end.startdate
  WHERE (period_end.startdate IS NULL)

But the last period will fall here.
We will assume that the last period is "closed" by the maximum namedate for, that is:
ddd	2019-01-01	2019-05-01
ddd	2019-05-02	2019-06-07
ddd	2019-06-10	2019-09-04
ddd	2019-09-05	2999-12-31
aaa	2019-09-01	2019-09-10
aaa	2019-09-12	2019-12-31
aaa	2020-01-01	2020-12-31

SELECT period.name, period.startdate, period.enddate
  FROM period 
    LEFT OUTER JOIN period AS period_end ON period.name = period_end.name 
                              AND DATEADD(dd, 1, period.enddate) = period_end.startdate
  WHERE (period_end.startdate IS NULL) 
     AND (period.enddate <> (SELECT MAX(enddate) FROM period AS period_last 
                                                 WHERE (name = period.name)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question