title: Looping SQL server records with GROUP BY to update value for the group
body: <p>I have a CustomerSales table that looks like below:</p>
  
  <pre><code>[RowID], [Cust], [Time], [Article], [Qty], [Amount], [Receipt]
  1, C1, 10:10:00, A1, 1, 100, 1
  2, C1, 10:10:00, A2, 2, 101, 1
  3, C1, 10:10:00, A3, 3, 102, 1 
  4, C1, 10:10:00, A4, 4, 103, 1
  5, C2, 10:10:11, A3, 5, 104, 1
  6, C3, 10:20:01, A2, 6, 105, 1
  7, C4, 10:20:01, A2, 7, 106, 1
  8, C4, 10:20:01, A1, 8, 107, 1
  9, C1, 11:11:01, A2, 3, 100, 1
  10, C1, 11:11:01, A3, 2, 101, 1
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/rHo8G.png" alt="CustomerSales table"></p>
  
  <p>My data does not have receipt number. Hence the requirement is to generate a linear number for receipt number. e.g. start from 1 and increments by 1. 
  To determine which line items belong to a given receipt number the records can be grouped by [Cust] and [Time]. All lines belonging to the group of [Cust] and [Time] will be updated with the MAX(Receipt]+1 (next available receipt number).</p>
  
  <p>Expected results as below:</p>
  
  <pre><code>[RowID], [Cust], [Time], [Article], [Qty], [Amount], [Receipt]
  1, C1, 10:10:00, A1, 1, 100, 1, 1
  2, C1, 10:10:00, A2, 2, 101, 1, 1
  3, C1, 10:10:00, A3, 3, 102, 1, 1 
  4, C1, 10:10:00, A4, 4, 103, 1, 1
  5, C2, 10:10:11, A3, 5, 104, 1, 2
  6, C3, 10:20:01, A2, 6, 105, 1, 3
  7, C4, 10:20:01, A2, 7, 106, 1, 4
  8, C4, 10:20:01, A1, 8, 107, 1, 4
  9, C1, 11:11:01, A2, 3, 100, 1, 5
  10, C1, 11:11:01, A3, 2, 101, 1, 5
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/jVCqC.png" alt="Expected Results"></p>