title: TSQL Group by Column with Multiple Values
body: <p>I have a table in SQLServer 2008r2 as below.</p>
  
  <p><a href="https://i.stack.imgur.com/hvgLy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hvgLy.png" alt="example dataset"></a></p>
  
  <p>I want to select all the records where the <code>[Fg]</code> column = 1 that consecutively by <code>[Id]</code> order lead into value 2 for each <code>[T_Id]</code> and <code>[N_Id]</code> combination.  </p>
  
  <p>There can be instances where record prior to <code>[Fg]</code> = 2 doesn't = 1</p>
  
  <p>There can be any number of records where the value of <code>[Fg]</code> = 1 but only one record where <code>[Fg]</code> = 2 for each <code>[T_Id]</code> and <code>[N_Id]</code> combination.</p>
  
  <p>So for the example below, I want to select records with <code>[Id]</code>s (4,5) and (7,8,9 )and (19,20).</p>
  
  <p>Any records for <code>[T_Id]</code> 3 and 4 are excluded.</p>
  
  <p><strong>Expected output</strong></p>
  
  <p><a href="https://i.stack.imgur.com/mzopx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mzopx.png" alt="Expected output"></a></p>
  
  <p>Example data set</p>
  
  <pre><code>DECLARE @Data TABLE ( Id INT IDENTITY (1,1), T_Id INT, N_Id INT, Fg TINYINT )
  
  INSERT INTO @Data
  (T_Id, N_Id, Fg)
  VALUES
  (1, 2, 0), (1, 2, 1), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 3, 0), (2, 3, 1), 
  (2, 3, 1), (2, 3, 2), (3, 4, 0), (3, 4, 0), (3, 4, 0), (3, 4, 2), (4, 5, 0), 
  (4, 5, 1), (4, 5, 0), (4, 5, 2), (5, 7, 0), (5, 7, 1), (5, 7, 2) 
  </code></pre>