Skip to content
Advertisement

Is a cursor/recursion the only possible option here? Set based logic based on certain lag conditions

I’m using SQL Server, I have a table with 3 columns (timeseries) data, with date, hour beginning, AwardStatus.

The award status for the most part is randomly generated. There can be two options, Awarded or Not Awarded.

However, the business requirement is that we MUST print ‘NotAwarded’ for 3 consecutive rows if the status is NotAwarded, and 4 consecutive rows if the status is Awarded.

Goal: a new column ShouldBe details.

Once it meets the minimum requirements, then it checks that the current row’s AwardStatus and continues to overwrite the logic.

Question: Is that possible in SQL without any kind of cursor/looping?

The picture in below as an example.

enter image description here

Here’s an example:

Advertisement

Answer

Since recursion was mentioned.

Here’s a solution that uses a recursive CTE.

Sample data:

Query:

Date                    | Hour | AwardStatus | NewAwardStatus
:---------------------- | ---: | :---------- | :-------------
2019-01-01 00:00:00.000 |    1 | NotAwarded  | NotAwarded    
2019-01-01 00:00:00.000 |    2 | NotAwarded  | NotAwarded    
2019-01-01 00:00:00.000 |    3 | Awarded     | NotAwarded    
2019-01-01 00:00:00.000 |    4 | Awarded     | Awarded       
2019-01-01 00:00:00.000 |    5 | NotAwarded  | Awarded       
2019-01-01 00:00:00.000 |    6 | NotAwarded  | Awarded       
2019-01-01 00:00:00.000 |    7 | Awarded     | Awarded       
2019-01-01 00:00:00.000 |    8 | NotAwarded  | NotAwarded    
2019-01-01 00:00:00.000 |    9 | Awarded     | NotAwarded    
2019-01-01 00:00:00.000 |   10 | Awarded     | NotAwarded    

A test on db<>fiddle here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement