Wednesday, January 29, 2014

FIll in missing months

Try this

declare @months table
(
monthnum int
--, mnthname varchar(3)
)
insert into @months

select MonthInt
from (
select 1 as MonthInt union all select 2 union all select 3 union all select 4 union all
select 5 as MonthInt union all select 6 union all select 7 union all select 8 union all
select 9 as MonthInt union all select 10 union all select 11 union all select 12
)M

declare @rider table(id int, rdt date, distance int);
insert into @rider values
(1, dateadd(m,-5,Getdate()),200),
(1, dateadd(m,-4,Getdate()),500),
(1, dateadd(m,-2,Getdate()),100),
(1, dateadd(m,-1,Getdate()),1000),
(1, dateadd(m,0,Getdate()),100),
(1, dateadd(m,2,Getdate()),550),
(1, dateadd(m,4,Getdate()),560);

with cte as
(select distinct id as riderid, m.monthnum from @rider r ,@months m )
select * from cte c left join @rider r on c.riderid=r.id and c.monthnum=month(r.rdt)





Satheesh

My Blog



No comments:

Post a Comment