title: SQL - Total Time on day
body: <p>My table looks a lot like the table shown in the following StackOverflow URL:
  <a href="https://stackoverflow.com/questions/26782860/calculating-total-time-excluding-overlapped-time-breaks-in-sqlserver">Calculating total time excluding overlapped time &amp; breaks in SQLServer</a></p>
  
  <p>My table also includes an OwnerID. Each person has an unique OwnerID, and I could easily join in the person name belonging to that ID.</p>
  
  <p>The result requested should be just like in the linked URL, but per Owner. I tried modifying the selected answer for his URL but that gives me the following error:   </p>
  
  <pre><code>The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
  </code></pre>
  
  <p>This is the query I try to run...</p>
  
  <pre><code> ;WITH addNR AS ( -- Add row numbers
  
  SELECT StartDate, EndDate, ROW_NUMBER() OVER (ORDER BY StartDate, EndDate) AS RowID
  FROM dbo.FollowUp AS T
  WHERE StartDate &gt; '2017-10-02 08:30:00.000'
  ), createNewTable AS ( -- Recreate table according overlap time
  
  SELECT StartDate, EndDate, RowID 
  FROM addNR
  WHERE RowID = 1
  
  UNION ALL
  
  SELECT 
      CASE 
          WHEN a.StartDate &lt;= AN.StartDate AND AN.StartDate &lt;= a.EndDate THEN a.StartDate 
          ELSE AN.StartDate END AS StartTime, 
      CASE WHEN a.StartDate &lt;= AN.EndDate AND AN.EndDate &lt;= a.EndDate THEN a.EndDate 
          ELSE AN.EndDate END AS EndTime,
      AN.RowID 
  FROM addNR AS AN
  INNER JOIN createNewTable AS a
      ON a.RowID + 1 = AN.RowID
  
  ), getMinutes AS ( -- Get difference in minutes
  SELECT DATEDIFF(MINUTE,StartDate,MAX(EndDate)) AS diffMinutes
  FROM createNewTable
  GROUP BY StartDate
  )
  SELECT SUM(diffMinutes) AS Result
  FROM getMinutes
  </code></pre>
  
  <p>Where I replaced StartTime=StartDate and EndTime=EndDate since my columns are named so..</p>
  
  <p><a href="https://i.stack.imgur.com/cEGRK.png" rel="nofollow noreferrer">Sample Data</a></p>