当前位置: 代码迷 >> Sql Server >> 走过路过帮忙写个SQL查询,该如何处理
  详细解决方案

走过路过帮忙写个SQL查询,该如何处理

热度:56   发布时间:2016-04-27 20:44:21.0
走过路过帮忙写个SQL查询
数据1
id is_one
1 0
2 1
3 1
4 0
5 0

数据2
id is_one
1 0
2 1
3 1
4 0
5 0
6 1
7 1
要统计最后1连续出现的次数,例如上面的数据1结果应该为0,数据2结果应该为2
这个语句应该这么写,不要用临时表或游标,谢谢


------解决方案--------------------

create table Test
(
id int,
is_one int
)

insert Test select 1,0
insert Test select 2,1
insert Test select 3,1
insert Test select 4,0
insert Test select 5,0
insert Test select 6,1
insert Test select 7,1
insert Test select 8,1
insert Test select 9,0

declare @max int
declare @max_1 int
declare @max_0 int
select @max=max(id) from Test
select @max_1=max(id) from Test where is_one=1
select @max_0=max(id) from Test where is_one=0

declare @sum int
set @sum=0

if @max <> @max_1
print @sum
else
begin
set @[email protected][email protected]_0
print @sum
end
  相关解决方案