Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query for month prior to last month

Author  Topic 

Petronas
Posting Yak Master

134 Posts

Posted - 2009-01-21 : 10:08:37
Hi All,

I need to get the order count of all orders prior to last month only. In jan, I need to get only the count for Nov. The below query is
pulling the count for both Nov as well as Dec. How do I just get it for Nov only?

select product_name, count(distinct(order_id),
convert(datetime,(convert(varchar(10),order_rcd_date,101)),101)
from orders
where order_rcd_date>convert(datetime,convert(varchar(11), dateadd(m,-2,getdate())))-datepart(dd,getdate())+1)
group by
product_name, convert(datetime,(convert(varchar(10),order_rcd_date,101)),101)


Thanks for your help,
Petronas

raky
Aged Yak Warrior

767 Posts

Posted - 2009-01-21 : 10:18:23
What is the datatype of order_rcd_date column ??

try this

select product_name, count(distinct(order_id),
convert(datetime,(convert(varchar(10),order_rcd_date,101)),101)
from orders
where DATEDIFF(mm,order_rcd_date,getdate()) = 2
group by
product_name, convert(datetime,(convert(varchar(10),order_rcd_date,101)),101)
Go to Top of Page

Petronas
Posting Yak Master

134 Posts

Posted - 2009-01-21 : 10:35:58
Thanks Raky,

It worked! Appreciate your help.

Thanks,
Petronas
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2009-01-21 : 10:38:32
welcome.....
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-21 : 11:07:02
if you want to use existing index on date field,

select product_name, count(distinct(order_id),
dateadd(dd,datediff(dd,0,order_rcd_date),0)
from orders
where order_rcd_date>=DATEADD(mm,DATEDIFF(mm,0,GETDATE())-2,0)
and order_rcd_date<DATEADD(mm,DATEDIFF(mm,0,GETDATE())-1,0)
group by
product_name, dateadd(dd,datediff(dd,0,order_rcd_date),0)
Go to Top of Page
   

- Advertisement -