日期:2014-05-19  浏览次数:20465 次

走过路过帮忙写个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 @sum=@max_1-@max_0
print @sum
end