 <p>You are looking for consecutive values. Here is one way, using a difference of row numbers to identify a group:</p> <pre><code>with t as (&lt;your query here&gt;) select min(term_start), max(term_end), block, quantity from (select t.*, (row_number() over (partition by block order by position) - row_number() over (partition by quantity, block order by position) ) as grp from t ) t group by quantity, grp, block; </code></pre>