SQL Server: Get data for only the past year

SqlSql ServerDatabaseTsql

Sql Problem Overview


I am writing a query in which I have to get the data for only the last year. What is the best way to do this?

SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'

Sql Solutions


Solution 1 - Sql

The following adds -1 years to the current date:

SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())

Solution 2 - Sql

I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.

At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.

SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))

Thanks to those above whose solutions helped me arrive at what I needed.

Solution 3 - Sql

Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1

Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'

Solution 4 - Sql

Look up dateadd in BOL

dateadd(yy,-1,getdate())

Solution 5 - Sql

The most readable, IMO:

SELECT * FROM TABLE WHERE Date >
   DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))

Which:

  1. Gets now's datetime GETDATE() = #8/27/2008 10:23am#
  2. Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
  3. Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
  4. Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#

There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).

Solution 6 - Sql

GETDATE() returns current date and time.

If last year starts in midnight of current day last year (like in original example) you should use something like:

DECLARE @start datetime
SET @start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) --  getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= @start

Solution 7 - Sql

I, like @D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. @samjudson's answer provides that. @D.E. White's answer returns results for the prior calendar year.

My query is a bit different in that it works for the prior year up to and including the current date:

SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))

For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017

Solution 8 - Sql

For some reason none of the results above worked for me.

This selects the last 365 days.

 SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()

Solution 9 - Sql

The other suggestions are good if you have "SQL only".

However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.

At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.

Solution 10 - Sql

argument for DATEADD function :

DATEADD (*datepart* , *number* , *date* )

datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms

number is an expression that can be resolved to an int that is added to a datepart of date

date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.

Solution 11 - Sql

declare @iMonth int
declare @sYear varchar(4)
declare @sMonth varchar(2)
set @iMonth = 0
while @iMonth > -12
begin
	set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
	set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
	select @sYear + @sMonth
	set @iMonth = @iMonth - 1
end

Solution 12 - Sql

I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):

SELECT ... FROM ....WHERE 
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >=  DATEADD(year,-1,GETDATE())

Solution 13 - Sql

Here's my version.

YEAR(NOW())- 1

Example:

YEAR(c.contractDate) =  YEAR(NOW())- 1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh MeinView Question on Stackoverflow
Solution 1 - SqlsamjudsonView Answer on Stackoverflow
Solution 2 - SqlD.E. WhiteView Answer on Stackoverflow
Solution 3 - SqlIvan BosnicView Answer on Stackoverflow
Solution 4 - SqlSQLMenaceView Answer on Stackoverflow
Solution 5 - SqlMark BrackettView Answer on Stackoverflow
Solution 6 - SqlGrzegorz GierlikView Answer on Stackoverflow
Solution 7 - SqlkevinaskevinView Answer on Stackoverflow
Solution 8 - SqlConnorView Answer on Stackoverflow
Solution 9 - SqlBlaMView Answer on Stackoverflow
Solution 10 - SqlimtherefView Answer on Stackoverflow
Solution 11 - SqlTonyView Answer on Stackoverflow
Solution 12 - SqlRick SavoyView Answer on Stackoverflow
Solution 13 - Sqllloydyu24View Answer on Stackoverflow