Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should point you in the right direction.</p> <p>You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer.</p> <pre><code>CREATE VIEW dbo.StudentStartDates AS SELECT S.StudentID, S.StartDate, S.Field1, S.Field2 FROM dbo.Students S LEFT OUTER JOIN dbo.Students PREV ON PREV.StudentID = S.StudentID AND PREV.Field1 = S.Field1 AND PREV.Field2 = S.Field2 AND PREV.EndDate = DATEADD(dy, -1, S.StartDate) WHERE PREV.StudentID IS NULL GO CREATE VIEW dbo.StudentEndDates AS SELECT S.StudentID, S.EndDate, S.Field1, S.Field2 FROM dbo.Students S LEFT OUTER JOIN dbo.Students NEXT ON NEXT.StudentID = S.StudentID AND NEXT.Field1 = S.Field1 AND NEXT.Field2 = S.Field2 AND NEXT.StartDate = DATEADD(dy, 1, S.EndDate) WHERE NEXT.StudentID IS NULL GO SELECT SD.StudentID, SD.StartDate, ED.EndDate, SD.Field1, SD.Field2 FROM dbo.StudentStartDates SD INNER JOIN dbo.StudentEndDates ED ON ED.StudentID = SD.StudentID AND ED.Field1 = SD.Field1 AND ED.Field2 = SD.Field2 AND ED.EndDate &gt; SD.StartDate AND NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate &lt; ED.EndDate AND ED2.EndDate &gt; SD.StartDate) GO </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload