日期:2014-05-18  浏览次数:20665 次

求教大家一个sql问题
有这样的数据列表
ID value
1 1
2 1
3 1
4 3
5 3
6 2
7 2
8 2
9 2
10 1
11 1
12 3
13 2
14 2
15 2
16 2
17 2
18 2
19 3
20 3
21 3
22 3
我想求出第一次连续出现1的次数和第二次连续出现2的次数,想到游标的方法,但是数据量大,耗时长,所以想求大家直接给出sql语句比较好,拜托各位大侠了

------解决方案--------------------
结果是什么样的?
------解决方案--------------------
SQL code

declare @tb table (id int identity, value int);
insert into @tb (value)
 select 1 union all select 1 union all select 1 union all
 select 3 union all select 3 union all select 2 union all
 select 2 union all select 2 union all select 2 union all
 select 1 union all select 1 union all select 3 union all
 select 2 union all select 2 union all select 2 union all 
 select 2 union all select 2 union all select 2 union all 
 select 3 union all select 3 union all select 3 union all 
 select 3;
 
with t as (
select id,value,ROW_NUMBER() over (partition by value order by id)-id grp 
from @tb where value in (1,2)
)
select value,COUNT(1) cnt from t group by grp,value order by value,MAX(id);
/*
1    3
1    2
2    4
2    6
*/

------解决方案--------------------
SQL code
create table tb(ID int,v int)
insert into tb select 1,1 union all select
2,1 union all select
3,1 union all select
4,3 union all select
5,3 union all select
6,2 union all select
7,2 union all select
8,2 union all select
9,2 union all select
10,1 union all select
11,1 union all select
12,3 union all select
13,2 union all select
14,2 union all select
15,2 union all select
16,2 union all select
17,2 union all select
18,2 union all select
19,3 union all select
20,3 union all select
21,3 union all select
22,3
go
select identity(int,1,1) as i,id,v into #t1 from tb a where not exists(select 1 from tb where v=a.v and id=a.id-1)
select identity(int,1,1) as i,id,v into #t2 from tb a where not exists(select 1 from tb where v=a.v and id=a.id+1)
select a.v,b.id-a.id+1 as dlt from #t1 a inner join #t2 b on a.i=b.i where a.v<3 order by a.i
go
drop table tb,#t1,#t2
/*
v           dlt
----------- -----------
1           3
2           4
1           2
2           6

(4 行受影响)
*/