[英]Sql Server - Constraint - Allow to set column A only if column B is null and vice-versa
[英]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.