use tempdb
go
if object_id('t') is not null drop table t
go
create table t (m varchar(1), n int)
insert into t
select 'a', 1 union all
select 'a', 3 union all
select 'a', 4 union all
select 'a', 4 union all
select 'a', 5 union all
select 'a', 6 union all
select 'a', 6 union all
select 'a', 6 union all
select 'a', 8 union all
select 'a', 9 union all
select 'b', 1 union all
select 'b', 1 union all
select 'b', 2 union all
select 'b', 2 union all
select 'b', 5
declare @t2 table(m char(1),n int)
declare @t3 table(m char(1),n int)
insert @t2
select distinct t1.m,cast(dateadd(day,num,(select min(t.n)-1 from t where t.m=t1.m group by t.m)) as int) n
from
(select b*100+c*10+d num from
(select 0 b union select 1 union select 2 union select 3 union select 4
union select 5 union select 6 union select 7 union select 8 union select 9) b
cross join
(select 0 c union select 1 union select 2 union select 3 union select 4
union select 5 union select 6 union select 7 union select 8 union select 9) c
cross join
(select 0 d union select 1 union select 2 union select 3 union select 4
union select 5 union select 6 union select 7 union select 8 union select 9) d) a, t t1
where cast(dateadd(day,num,(select min(t.n)-1 from t where t.m=t1.m group by t.m)) as int)<=(select max(t.n)from t where t.m=t1.m group by t.m)
and cast(dateadd(day,num,(select min(t.n)-1 from t where t.m=t1.m group by t.m)) as int) not in (select t.n from t where t.m=t1.m)
insert @t3
select distinct t1.m,cast(dateadd(day,num,(select min(t.n) from t where t.m=t1.m group by t.m)) as int) n
from
(select b*100+c*10+d num from
(select 0 b union select 1 union select 2 union select 3 union select 4
union select 5 union select 6 union select 7 union select 8 union select 9) b
cross join
(select 0 c union select 1 union select 2 union select 3 union select 4
union select 5 union select 6 union select 7 union select 8 union select 9) c
cross join
(select 0 d union select 1 union select 2 union select 3 union select 4
union select 5 union select 6 union select 7 union select 8 union select 9) d) a, t t1
where cast(dateadd(day,num,(select min(t.n) from t where t.m=t1.m group by t.m)) as int)<=(select max(t.n)+1 from t where t.m=t1.m group by t.m)
and cast(dateadd(day,num,(select min(t.n) from t where t.m=t1.m group by t.m)) as int) not in (select t.n from t where t.m=t1.m)
select u.m,u.l nMin,min(v.r) nMax
from
(select t2.m, (select min(t.n) from t where t.n>t2.n and t.m=t2.m) l from @t2 t2) u,
(select t3.m, (select max(t.n) from t where t.n<t3.n and t.m=t3.m) r from @t3 t3) v
where u.l<=v.r and u.m=v.m
group by u.m,u.l
order by 1
go |