Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query to Select Records for 12 rolling months 1

Status
Not open for further replies.

BHaines

Programmer
May 29, 2003
100
US
*gnaws on Mouse cord* Recently reintroduced to querying SQL, and at an absolute loss on how to get it to only feed me records for the 12 months prior to the current month (last 12 full months in other words)based on a datetime field in the database. I can get it to do this year and last year, but that isn't what's required. Any help will be much appreciated. (This will eventually create a temp table for a stored procedure for a Crystal Report)

What I have thus far which gets me only records from 2004 and 2005, and is probably way off what I actually need to do:

Code:
Select CREATED from dbo.S_SRV_REQ 
WHERE Datename(yy,CREATED) BETWEEN Datename(yy,dateadd(yyyy,-1,GETDATE())) AND Datename(yy,GETDATE())
 
One way:

Code:
DECLARE @start datetime,
  @end datetime

SET @start = CONVERT(varchar(6), DATEADD(mm, -13, GETDATE()), 112) + '01'
SET @end = CONVERT(varchar(6), GETDATE(), 112) + '01'

SELECT col_list
FROM table_name
WHERE date_field >= @start
  AND date_field < @end

--James
 
You rock my world! That worked PERFECTLY! Thank you so much!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top