Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Get data for only the past year

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' 
like image 282
Josh Mein Avatar asked Aug 27 '08 14:08

Josh Mein


People also ask

How do I keep just the year from a date in SQL?

If you need to store a year in the database, you would either want to use an Integer datatype (if you are dead set on only storing the year) or a DateTime datatype (which would involve storing a date that basically is 1/1/1990 00:00:00 in format). – KM. @KM.

How do I get last 6 months data in SQL?

Instead of approximating the "current" date by selecting the MAX(date) the code could reference CAST(GETDATE() as DATE) to access the system datetime and cast it as type DATE. where [date] > dateadd(month, -6, cast(getdate() as date));


2 Answers

The following adds -1 years to the current date:

SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE()) 
like image 79
samjudson Avatar answered Oct 30 '22 02:10

samjudson


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.

like image 21
D.E. White Avatar answered Oct 30 '22 00:10

D.E. White