Welcome to Microsoft T-SQL Q&A Forum!
Please try this:
create table #t (Id int identity(1,1), Name char)
insert into #t values
('0'),
('1'),
('1'),
('0'),
('0'),
('1'),
('0'),
('0'),
('1')
WITH cte AS (
SELECT Id, Name,
grp = CASE WHEN Name =1 AND prev=0 THEN 1 ELSE 0 END
FROM (SELECT *, prev = LAG(Name) OVER(ORDER BY id) FROM #t) s
)
SELECT Sum(GRP) as count
FROM CTE
Best regards,
Bert Zhou
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.