简体   繁体   中英

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

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
select count(*) from (
 select case when col1 <> lag(col1,1,col1) over (order by id) then 1 end rn
from table 
) t 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM