10

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)
1
  • Additional quotes? Do you mean parentheses? Tip: It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers.
    – HABO
    Nov 21, 2015 at 21:44

5 Answers 5

15

If you use SQL Server 2012+ use DATEFROMPARTS:

SELECT DATEFROMPARTS ( DATEPART(yyyy, GETDATE()) - 1, 1, 1 )

db<>fiddle demo

6

got it to work

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

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
1

Another method is:

select dateadd(year, -1, datename(year, getdate()) + '0101')
0

Use this: SELECT DATEFROMPARTS(YEAR(GETDATE())-1,1,1)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.