|
Petronas
Posting Yak Master
134 Posts |
Posted - 2009-07-21 : 10:29:00
|
| Hi,I need to loop through to get counts for each month from 2/1/2009 to now.I am not sure how do I proceed after the select statement?Thanks,PetronasQueryDECLARE @now datetime, @cnt int, @start_date DATETIME, @end_date DATETIMESET @now = GETDATE()SET @CNT = datediff(mm,'2/1/2009',@now)WHILE (@CNT > 0)BEGINSELECT @start_date = DATEADD(mm,-@cnt,CONVERT(varchar,DATEADD(dd,-DAY(@now)+1,@now),111))SELECT @end_date = DATEADD(mm,1,@start_date)if object_id('#temp1') is not null drop table #temp1--if object_id('#temp2') is not null drop table #temp2select distinct(o.order_id),o.product_id, convert(datetime,convert(varchar(2), month(order_Received_date)) +'/1/' + convert(varchar(4), year (order_Received_date)))order_Received_date,b.bill_sent_date,b.bill_response_date,convert(varchar(11),o.cancel_date,110)cancel_date,max(case when b.billing_cycle =1 then convert(varchar(11),b.bill_date,110) end) as First_Billing_dateinto #temp1 from orders_base o (nolock) inner join V_billingwithhistory b(nolock) On o.order_id=b.order_idwhere o.product_id ='quality' and b.response_type_id = 'a' and o.order_received_date < @start_dateand (o.cancel_date is null or o.cancel_date >=@start_date)and b.bill_date between convert(datetime,convert(varchar(11), dateadd(m,-1,@start_date)))- datepart(dd,@start_date) + 1 and convert(datetime,convert(varchar(11), @start_date))- datepart(dd,@start_date + 1 )and b.response_date between convert(datetime,convert(varchar(11), dateadd(m,-1,@start_date)))- datepart(dd,@start_date) + 1 and convert(datetime,convert(varchar(11), @start_date))- datepart(dd,@start_date + 1 )--and b.first_billing_date is not null group by o.order_id,o.product_id,convert(datetime,convert(varchar(2), month(order_Received_date)) +'/1/' + convert(varchar(4), year (order_Received_date))),convert(varchar(11),o.cancel_date,110),b.bill_date,b.response_date--select * from #temp1SELECT @CNT = @CNT - 1END |
|