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

sql 语句觉得难不会
测试数据
name updatetime
a 2012-03-08
a 2012-03-09
a 2012-03-17
a 2012-03-18
b 2012-03-14
b 2012-03-15
b 2012-03-16
b 2012-03-17
b 2012-03-18
b 2012-03-19
b 2012-03-20
b 2012-03-21
c 2012-03-12
c 2012-03-13
c 2012-03-15
c 2012-03-16
c 2012-03-19
c 2012-03-20
c 2012-03-21
结果
name mintime maxtime
a 2012-03-08 2012-03-09
a 2012-03-17 2012-03-18
b 2012-03-14 NULL
c 2012-03-12 2012-03-13
c 2012-03-15 2012-03-16
c 2012-03-19 NULL
连续时间段取最大,最小时间
如果当前时间还有这个name,那么就最大时间为空

------解决方案--------------------
SQL code

--> 测试数据:[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
*/

第一次解决这样的问题,不知道是不是你要的结果