Skip to content
Advertisement

How to get row number for each null value?

I need to get row number for each record of null by sequence. Restart number when get a value in the row.

I have tried so far

I’m getting this:

I want a result like this

How can I get desired result with sql query?

Advertisement

Answer

This approach uses COUNT as an analytic function over the value column to generate “groups” for each block of NULL values. To see how this works, just run SELECT * FROM cte using the code below. Then, using this computed group, we use ROW_NUMBER to generate the sequences for the NULL values. We order ascending by the value, which would mean that each NULL row number sequence would always begin with 1, which is the behavior we want. For records with a non NULL value, we just pull that value across into the rn column.

enter image description here

Demo

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