title: Query statement that loops through unique ID's in SQL Server
body: <p>I have a query statement that finds time gaps in my data set. It works great except that I have 100's of unique ID's I need to run it through. Rather than manually entering the SerialNum, is there a way to run this query statement through each SerialNum in the table? I'm thinking it needs to be a for each loop but don't know how to set that up. </p>
  
  <pre><code>    WITH ordered AS
  (
      SELECT *, ROW_NUMBER() OVER (ORDER BY DateYearAndJulian) rn
      FROM table
      WHERE SerialNum = '040142'
      )
  SELECT o1.SerialNum SerialNum1, o1.DateYearAndJulian DateYearAndJulian1, o2.SerialNum SerialNum2, o2.DateYearAndJulian DateYearAndJulian2, DATEDIFF(hh, o1.DateYearAndJulian, o2.DateYearAndJulian) diff
  FROM ordered o1 JOIN ordered o2
      ON o1.rn + 1 = o2.rn
  WHERE DATEDIFF(hh, o1.DateYearAndJulian, o2.DateYearAndJulian) &gt; 13
  </code></pre>
  
  <p>The result looks like:</p>
  
  <pre><code>040142  2018-01-07 22:00:00.0000000 040142  2018-01-16 00:00:00.0000000 194
  040142  2019-12-09 16:00:00.0000000 040142  2019-12-10 18:00:00.0000000 26
  040142  2020-01-10 22:00:00.0000000 040142  2020-01-12 04:50:00.0000000 30
  040142  2018-08-18 23:00:00.0000000 040142  2018-08-21 03:00:00.0000000 52
  </code></pre>