SQL 查询显示计数,表中 SQL Server 中行从 -1 变为 1 的次数,反之亦然。
设表名A
col1
-----
1
-1
-1
1
1
-1
答案 0 :(得分: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
答案 1 :(得分:-1)
select count(*) from (
select case when col1 <> lag(col1,1,col1) over (order by id) then 1 end rn
from table
) t