Skip to content
Advertisement

Group rows by dense_rank() and loop through each sub-group and compare another column in next row of that sub group?

I have tried the following in LINQPad:

enter image description here

I want to write a query which will return only the IDs 1 and 2 (not 3 and 4) because:

  • ID 1 – has more than 1 rows and startdate of its rownum 2 is 1 day ahead of enddate of its rownum 1
  • ID 2 – has more than 1 rows and startdate of its rownum n + 1 is 1 day ahead of enddate of its rownum n
  • ID 3 – THOUGH has more than 1 rows, startdate of its rownum 3 is NOT 1 day ahead (but 2 days) of enddate of its rownum 2. Hence, it is not qualified
  • ID 4 – DOES NOT HAVE more than 1 rows. Hence, it is not qualified

Could you let me know how to get this result please?

Advertisement

Answer

You could use window function lag() to recover the previous enddate, then aggregation and filter in the having clause:

Demo on DB Fiddle:

| id |
| -: |
|  1 |
|  2 |

In archaic versions of SQL Server, that do not support window functions, you can emulate lag() with a correlated subquery:

Demo on DB Fiddle

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