Skip to content
Advertisement

Want the count how many times row changes from -1 to 1 or vice-versa in SQL Server

SQL query to display the count, how many times row changes from -1 to 1 or vice-versa in SQL Server in a table.

Let the table name be A

col1
-----
1
-1
-1
1
1
-1

Advertisement

Answer

For this question to have an answer, you need a column that specifies the ordering. SQL tables represent unordered (multi)sets. There is no inherent ordering. To answer your question, you can use lag() and conditional aggregation:

select sum(case when col1 = -1 and prev_col1 = 1 then 1 else 0
           end) as change_minus_to_plus,
       sum(case when col1 = 1 and prev_col1 = -1 then 1 else 0
           end) as change_plus_to_minus
from (select t.*,
             lag(col1) over (order by <ordering col<) as prev_col1
      from t
     ) t
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement