日期:2014-05-18 浏览次数:20670 次
--> 测试数据:[tbl]
go
if object_id('[tbl]') is not null
drop table [tbl]
go
create table [tbl](
[name] varchar(1),
[updatetime] datetime
)
go
insert [tbl]
select 'a','2012-03-08' union all
select 'a','2012-03-09' union all
select 'a','2012-03-17' union all
select 'a','2012-03-18' union all
select 'b','2012-03-14' union all
select 'b','2012-03-15' union all
select 'b','2012-03-16' union all
select 'b','2012-03-17' union all
select 'b','2012-03-18' union all
select 'b','2012-03-19' union all
select 'b','2012-03-20' union all
select 'b','2012-03-21' union all
select 'c','2012-03-12' union all
select 'c','2012-03-13' union all
select 'c','2012-03-15' union all
select 'c','2012-03-16' union all
select 'c','2012-03-19' union all
select 'c','2012-03-20' union all
select 'c','2012-03-21'
;with t
as(
select ROW_NUMBER()over(PARTITION by name order by updatetime) as id,* from tbl a
where not exists(select 1 from tbl b
where b.updatetime=DATEADD(DD,-1,a.updatetime) and b.name=a.name)
),m as(
select ROW_NUMBER()over(PARTITION by name order by updatetime) as id,* from tbl a
where not exists(select 1 from tbl b
where b.updatetime=DATEADD(DD,1,a.updatetime) and b.name=a.name)
)
select t.name,t.updatetime as mindate,
(case when convert(varchar(10),m.updatetime,120)=convert(varchar(10),GETDATE(),120) then null
else m.updatetime end) as maxdate
from t inner join m on t.id=m.id and t.name=m.name
/*
name mindate maxdate
a 2012-03-08 00:00:00.000 2012-03-09 00:00:00.000
a 2012-03-17 00:00:00.000 2012-03-18 00:00:00.000
b 2012-03-14 00:00:00.000 NULL
c 2012-03-12 00:00:00.000 2012-03-13 00:00:00.000
c 2012-03-15 00:00:00.000 2012-03-16 00:00:00.000
c 2012-03-19 00:00:00.000 NULL
*/
第一次解决这样的问题,不知道是不是你要的结果