Query To Identify Contiguous Ranges
I'm trying to write a query on the below data set to add a new column which has some sort of 'period_id_group'. contiguous new_period row_nr new_period_starting_id 0 0
Solution 1:
So, if I'm understanding you correctly, you just need one additional column.
SELECT t1.contiguous, t1.new_period, t1.row_nr, t1.new_period_starting_id,
(SELECT TOP 1 (new_period_starting_id)
FROM YourTable t2
WHERE t2.row_nr <= t1.row_nr
AND t2.period_id_group >0/* optimization */ORDERBY t2.row_nr DESC/* optimization */) AS period_id_group
FROM YourTable t1
Solution 2:
Here is yet another option for this.
selectt1.contiguous
, t1.new_period
, t1.row_nr
, t1.new_period_starting_id
, x.new_period_starting_idfrom @tmp2t1outerapply
(
select top 1 *
from @tmp2 t2
where (t2.row_nr = 1or t2.new_period_starting_id > 0)
and t1.row_nr >= t2.row_nr
order by t2.row_nr desc
) x
Post a Comment for "Query To Identify Contiguous Ranges"