Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find data from this day exactly one year ago?

Tags:

Right now I have:

year(epe_curremploymentdate) = year(DATEADD(year, -1, SYSDATETIME())) 

But that is giving me everything from last year. All I want is the data from today's date, one year ago.

like image 937
user3630473 Avatar asked Jun 20 '14 20:06

user3630473


People also ask

How do I subtract a day from a date in SQL?

Following the answer from Philip Rego, you can use SELECT GETDATE() - 1 to subtract days from a date.


2 Answers

It should be:

epe_curremploymentdate = DATEADD(year, -1, GETDATE())

Don't check for year in your where clause.

EDIT:

Simple: use

cast(epe_curremploymentdate AS DATE) = cast(DATEADD(year, -1,
  GETDATE()) AS DATE)

That is, if you are using SQL Server 2008 and above.

like image 175
Karthik Ganesan Avatar answered Oct 06 '22 01:10

Karthik Ganesan


This should get you to where you need to go:

Declare @StartDate datetime, @EndDate datetime

-- @StartDate is midnight on today's date, last year
set @StartDate = Convert(date, (DATEADD(year, -1, getdate()))) 
set @EndDate = DATEADD(Day, 1, @StartDate)

select * 
from YourTable 
where epe_curremploymentdate >= @StartDate 
    and epe_curremploymentdate < @EndDate

-- This where clause will get you everything that happened at any time 
-- on today's date last year.
like image 44
Dean Avatar answered Oct 05 '22 23:10

Dean