title: SQL - Start and End date based on another column
body: <p>Simplified structure.</p>
  
  <p>I need the two dates between a record that has an action type of 4 and an action type of 1. </p>
  
  <p>The record could be in that state multiple times and I would need separate rows for their times</p>
  
  <p>For example for IncidentId = 1</p>
  
  <ul>
  <li>Row 1 - StartTime = 2017-01-01 14:00 (id:3) - End Time = 2017-01-01 20:00 (id: 5)</li>
  <li>Row 2 - StartTime = 2017-01-01 21:00 (id:6) - End Time = 2017-01-02 11:00 (id: 9)</li>
  </ul>
  
  <pre>
  
      CREATE TABLE #returntable 
        ( 
           [incidentid] INT, 
           [starttime]  DATETIME, 
           [endtime]    DATETIME 
        ) 
  
      CREATE TABLE #testtableofdoom 
        ( 
           [incidentlogid] INT, 
           [incidentid]    INT, 
           [timestamp]     DATETIME, 
           [actiontypeid]  INT 
        ) 
  
       INSERT INTO #testtableofdoom
              ( incidentlogid, incidentid, timestamp, actiontypeid )
       VALUES ( 1, 1, '2017-01-01 09:00', 1 )
          ,   ( 2, 1, '2017-01-01 11:00', 1 )
          ,   ( 3, 1, '2017-01-01 14:00', 4 )
          ,   ( 4, 1, '2017-01-01 16:00', 4 )
          ,   ( 5, 1, '2017-01-01 20:00', 1 )
          ,   ( 6, 1, '2017-01-01 21:00', 4 )
          ,   ( 7, 1, '2017-01-02 09:00', 4 )
          ,   ( 8, 2, '2017-01-02 10:00', 1 )
          ,   ( 9, 1, '2017-01-02 11:00', 1 )
          ,   ( 10, 1, '2017-01-02 14:00', 1 )
          ,   ( 11, 2, '2017-01-02 15:00', 4 )
          ,   ( 12, 1, '2017-01-02 16:00', 1 )    
          ,   ( 13, 1, '2017-01-02 17:00', 1 )
          ,   ( 14, 1, '2017-01-02 18:00', 1 )
          ,   ( 15, 2, '2017-01-02 15:00', 1 );
  
      DROP TABLE #testtableofdoom 
  
      DROP TABLE #returntable 
  
  </pre>