Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This query uses CTEs to: </p> <ol> <li>Create an ordered collection of records grouped by Registration</li> <li>For each record, capture the data of the previous record</li> <li>Compare current and previous data to determine if the current record is a new instance of a driver / trailer assignment</li> <li>Get only the new records</li> <li>For each new record, get the last date before a new driver / trailer assignment occurs</li> </ol> <p>Link to <a href="http://sqlfiddle.com/#!3/b8592/2/0" rel="nofollow">SQL Fiddle</a></p> <p>Code below:</p> <pre><code>;WITH c AS ( -- Group records by Registration, assign row numbers in order of date SELECT ROW_NUMBER() OVER ( PARTITION BY Registration ORDER BY Registration, [Date]) AS Rn, Registration, [Date], DriverID, TrailerID FROM TempTable ) ,c2 AS ( -- Self join to table to get Driver and Trailer from previous record SELECT t1.Rn, t1.Registration, t1.[Date], t1.DriverID, t1.TrailerID, t2.DriverID AS PrevDriverID, t2.TrailerID AS PrevTrailerID FROM c t1 LEFT OUTER JOIN c t2 ON t1.Registration = t2.Registration AND t2.Rn = t1.Rn - 1 ) ,c3 AS ( -- Use INTERSECT to determine if this record is new in sequence SELECT Rn, Registration, [Date], DriverID, TrailerID, CASE WHEN NOT EXISTS ( SELECT DriverID, TrailerID INTERSECT SELECT PrevDriverID, PrevTrailerID) THEN 1 ELSE 0 END AS IsNew FROM c2 ) -- For all new records in sequence, -- get the last date logged before a new record appeared SELECT Registration, [Date] AS StartDate, COALESCE ( ( SELECT TOP 1 [Date] FROM c3 WHERE Registration = t.Registration AND Rn &lt; ( SELECT TOP 1 Rn FROM c3 WHERE Registration = t.Registration AND Rn &gt; t.Rn AND IsNew = 1 ORDER BY Rn ) ORDER BY Rn DESC ) , [Date]) AS EndDate, DriverID, TrailerID FROM c3 t WHERE IsNew = 1 ORDER BY Registration, StartDate </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.
    3. 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