Skip to content
Advertisement

Get values “0” and “1” alternated rows on SQL

I’m using SQL Server 2015, I have a table with a list of values “name”, my necessity is to add a column that alternate values “0” and “1” when the “name” columns changes. This is important for me because, I import this query on excel, and I will format the rows with conditional formatting reading the value of “trig”. This is an example of desidered result.

Thank you

Advertisement

Answer

You could use DENSE_RANK here:

screen capture from demo link below

Demo

The logic here is that DENSE_RANK will return a value, starting with 1, for each group of name records. We can take the mod 2 of this value to obtain 0 or 1 alternatively for each name.

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