Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting First Date of previous year

how can I modify the statement below to get first date of previous year (Preferably without introducing additional quotes)

SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), -1)
like image 240
HDB Avatar asked Nov 21 '15 15:11

HDB


2 Answers

The better answer is:

SELECT DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)

If you understand how the original works, you know where to put the -1.

The arguments for DATEADD are DATEADD(interval, increment int, expression smalldatetime).

So in the expression above, the DATEDIFF function returns an integer, being the difference in years between the current date and date zero (0).

The expression in the above statement accepts a zero (0) as a smalldatetime.

So it adds the number of years between "date zero" and the "current date" to date zero.

Date zero is 1 Jan 1900, so that will give you 1 Jan for whatever the provided date is.

The following gives you the zero date:

select dateadd(yy,0,0)

So to go back one more year, you simply subtract 1 from the interval, so the interval becomes:

DATEDIFF(yy,0,GETDATE())-1
like image 100
tone Avatar answered Oct 07 '22 10:10

tone


got it to work

DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
like image 38
HDB Avatar answered Oct 07 '22 12:10

HDB