January 19, 2011 at 7:06 am
im using the query below to select data for a period of one year using DateTimeIn as the date parameter. if say we are in Jan 2011, i would leave out any data for Jan 2010. does anyone know what i must do to achieve this.
The query below has a problem when i add the following part
and (month(DateTimeIn) <> month(getdate()) and year(DateTimeIn) <> year(getdate())-1);
select *,'Enq' as Dtype from vwQV_Enquiry where ProformaCount = 0 and DateTimeIn >= dateadd(month,-12,getdate()) and PI not in (17,18)and (month(DateTimeIn) <> month(getdate()) and year(DateTimeIn) <> year(getdate())-1);
Thanks
January 19, 2011 at 7:57 am
Unless I'm misreading it, it seems like you only want to go back 11 months when filtering on DateTimeIn.
DECLARE @StartDate DATETIME
SET @StartDate = CAST(CAST(Month(GETDATE()) AS CHAR(2)) + '/1/' + CAST(YEAR(GETDATE()) AS CHAR(4)) AS DATETIME)
SELECT DATEADD(MONTH,-11,@StartDate)
_____________________________________________________________________
- Nate
January 19, 2011 at 10:00 am
You should use DateDiff() instead. Converting datetime data back and forth between char data is inefficient.
WHERE DateDiff(Month, DateTimeIn, GetDate()) < 12
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA
January 19, 2011 at 10:34 am
It is best to do the selection on a date range, and not use a selection where your column is in a function call. If your column is used in a function call, the query will not be able to use an index on the column.
select
*
from
MyTable
where
-- Select all data for prior 11 months and current month
-- GE 11th prior month
DateTimeIn >= dateadd(mm,datediff(mm,0,getdate())-11,0)and
-- Before start of next month
DateTimeIn < dateadd(mm,datediff(mm,0,getdate())+1,0)
January 19, 2011 at 11:37 pm
thansk unfortunately i dint want to use cursors. thanks for your help, i appreciate it.
January 19, 2011 at 11:39 pm
@SSCrazy
thansk it worked, and thanks to all you guys you helped me.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply