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.

+-----+--------+
| trig|  name  |
|-----+--------|
|  0  |  0400  |
|  0  |  0400  |
|  1  |  0150  |
|  1  |  0150  |
|  1  |  0150  |
|  0  |  0111  |
|  0  |  0111  |
+-----+--------+

Thank you

Advertisement

Answer

You could use DENSE_RANK here:

SELECT name, (DENSE_RANK() OVER (ORDER BY name) - 1) % 2 AS trig
FROM yourTable
ORDER BY name;

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