繁体   English   中英

想要计算 SQL 服务器中行从 -1 变为 1 或反之的次数

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

SQL 查询在 SQL 表中显示计数,行从 -1 变为 1 或反之的次数。

设表名为A

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

要让这个问题有答案,您需要一个指定顺序的列。 SQL 表表示无序(多)集。 没有固有的顺序。 要回答您的问题,您可以使用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.

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