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)
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)
5条答案
按热度按时间vngu2lb81#
If you use
SQL Server 2012+
useDATEFROMPARTS
:db<>fiddle demo
nnvyjq4y2#
got it to work
wlsrxk513#
The better answer is:
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:
So to go back one more year, you simply subtract 1 from the interval, so the interval becomes:
iyr7buue4#
Another method is:
qij5mzcb5#
Use this: SELECT DATEFROMPARTS(YEAR(GETDATE())-1,1,1)