[英]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. SQL 查询在 SQL 表中显示计数,行从 -1 变为 1 或反之的次数。
Let the table name be A
设表名为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. SQL 表表示无序(多)集。 There is no inherent ordering.没有固有的顺序。 To answer your question, you can use lag()
and conditional aggregation:要回答您的问题,您可以使用lag()
和条件聚合:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.