Skip to content
Advertisement

SQL increment counter that resets on zero – Optimization?

I have a table that contains consecutive dates and integers.

My goal is to add a counter that increments as each integer is zero and resets back to 1 if the integer is non-zero. I’m hoping that this can be optimized a bit as it can be an expensive query when run on the entire table.

Below is the code that is working. Thanks to everyone that takes a look.

Advertisement

Answer

This is a type of gaps-and-islands problem.

There are many solutions, here is one

  • Use a running conditional count to get an ID for each island
  • Genrate a row number partitioned by that ID

db<>fiddle

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