How do I find the minimum value greater than the previous row?
This code needs to be optimized to run over million rows and business keys, we may have 3-10 timevalue columns at most. I am thinking its some type of recursive CTE.
background: conducting slowly changing dimensions for many tables which are being denormalized. And trying to find proper begin dates.
Data Sample:
create table dbo.timetest
(
TimeTestIdentityId int primary key identity(1,1),
businesskey int,
timevalue1 int,
timevalue2 int,
timevalue3 int
)
insert into timetest
values
(5,131,134,137),
(5,131,138,135),
(5,131,140,135),
(5,143,141,145),
(5,149,141,148),
(5,150,141,148),
(6,134,137,140),
(6,134,141,138),
(6,134,143,138),
(6,146,144,148),
(6,152,144,151),
(6,153,144,151)
Final Values:
,etc
Row are ordered by TimeValue1.
Best Answer
My solution using a cursor and a temporary table, I can imagine another solution, but it involves an expensive recursive query.
db<>fiddle here
Using a recursive CTE:
db<>fiddle here