Question : T-Sql Query problem

Hi, I am having data in a table  as below.

DMDGROUP      WEEKDATE      QTY
9896138670      6/10/2008      5
9896138670      13/10/2008      6
9896138670      27/10/2008      11
9896138670      3/11/2008      8
9896138670      10/11/2008      7
9896138670      1/12/2008      9
9896138670      8/12/2008      6
9885544076      13/10/2008      4
9885544076      3/11/2008      3
9885544076      10/11/2008      8
9885544076      17/11/2008      10
9885544076      1/12/2008      1

Now, I would like to include missing weeks with columns having QTY=0 and also the weekcount starting from 1 for each DMDGROUP. So, it looks like the below table.


DMDGROUP      WEEKDATE      QTY      weekcount
9896138670      6/10/2008      5      1
9896138670      13/10/2008      6      2
9896138670      20/10/2008      0      3
9896138670      27/10/2008      11      4
9896138670      3/11/2008      8      5
9896138670      10/11/2008      7      6
9896138670      17/11/2008      0      7
9896138670      24/11/2008      0      8
9896138670      1/12/2008      9      9
9896138670      8/12/2008      6      10
9885544076      13/10/2008      4      1
9885544076      20/10/2008      0      2
9885544076      27/10/2008      0      3
9885544076      3/11/2008      3      4
9885544076      10/11/2008      8      5
9885544076      17/11/2008      10      6
9885544076      24/11/2008      0      7
9885544076      1/12/2008      1      8



Can someone help me with as soon as possible.

Thanks

Answer : T-Sql Query problem

;with dg as (select DMDGROUP,MIN(Weekdate) as Week1, MAX(WEEKDATE) as LastWeek from tbl group by DMDGROUP)
select dg.DMDGROUP,wk.WeekDate,isnull(t.QTY,0),wk.WeekNo
FROM dg
cross apply (
      select w.number+1 as WeekNo, dateadd(wk,w.number,dg.Week1) as WeekDate
      from master..spt_values w
      where w.type='P' and w.number<=DATEDIFF(WK,dg.Week1,dg.LastWeek)) wk
left join tbl t on t.DMDGROUP=dg.DMDGROUP and t.WEEKDATE=wk.WeekDate
order by dg.DMDGROUP,wk.WeekDate
Random Solutions  
 
programming4us programming4us