日期:2014-05-17 浏览次数:20645 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [id] int, [dateTime] datetime, [data] int ) go insert [test] select 1,'2011-08-10 04:06:00.000',0 union all select 2,'2011-08-10 05:06:00.000',1 union all select 3,'2011-09-11 01:00:00.000',1 union all select 4,'2011-09-12 02:00:00.000',1 union all select 5,'2011-10-12 23:53:00.000',0 union all select 6,'2011-10-12 23:53:00.000',0 union all select 7,'2011-10-12 23:53:00.000',0 union all select 8,'2011-10-12 23:53:00.000',0 union all select 9,'2011-10-12 23:53:00.000',0 union all select 10,'2011-10-12 23:53:00.000',1 union all select 11,'2011-10-12 23:53:00.000',1 union all select 12,'2011-10-12 23:53:00.000',1 union all select 13,'2011-10-12 23:53:00.000',1 union all select 14,'2011-10-12 23:54:00.000',1 union all select 15,'2011-10-12 23:54:00.000',1 go select * from test a where (exists(select 1 from test b where a.id=b.id+1 and b.data=1) or exists(select 1 from test c where a.id=c.id-1 and c.data=1)) and a.data=1 /* id dateTime data ------------------------------------ 2 2011-08-10 05:06:00.000 1 3 2011-09-11 01:00:00.000 1 4 2011-09-12 02:00:00.000 1 10 2011-10-12 23:53:00.000 1 11 2011-10-12 23:53:00.000 1 12 2011-10-12 23:53:00.000 1 13 2011-10-12 23:53:00.000 1 14 2011-10-12 23:54:00.000 1 15 2011-10-12 23:54:00.000 1 */ --把这个连续为1的给你筛选出来了,至于你说的累年什么的不懂。
------解决方案--------------------
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test](
[id] int,
[dateTime] datetime,
[data] int
)
go
insert [test]
select 1,'2011-08-10 04:06:00.000',0 union all
select 2,'2011-08-10 05:06:00.000',1 union all
select 3,'2011-09-11 01:00:00.000',1 union all
select 4,'2011-09-12 02:00:00.000',1 union all
select 5,'2011-10-12 23:53:00.000',0 union all
select 6,'2011-10-12 23:53:00.000',0 union all
select 7,'2011-10-12 23:53:00.000',0 union all
select 8,'2011-10-12 23:53:00.000',0 union all
select 9,'2011-10-12 23:53:00.000',0 union all
select 10,'2011-10-12 23:53:00.000',1 union all
select 11,'2011-10-12 23:53:00.000',1 union all
select 12,'2011-10-12 23:53:00.000',1 union all
select 13,'2011-10-12 23:53:00.000',1 union all
select 14,'2011-10-12 23:54:00.000',1 union all
select 15,'2011-10-12 23:54:00.000',1
go
;with cte as( select *, case when data=1 then 1 else 0 end as r from [test] where id=1 union all select t.*, case when t.data=1 and c.r=0 then 1 when t.data=1 and c.r>0 then abs(c.r) when t.data=0 and c.r>0 then -(c.r) when t.data=0 and c.r<0 then c.r when t.data=1 and c.r<0 th