SQL 获取上一年的第一个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33844830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting First Date of previous year
提问by HDB
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)
回答by Lukasz Szozda
If you use SQL Server 2012+
use DATEFROMPARTS
:
如果您使用SQL Server 2012+
使用DATEFROMPARTS
:
SELECT DATEFROMPARTS ( DATEPART(yyyy, GETDATE()) - 1, 1, 1 )
回答by HDB
got it to work
让它工作
DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
回答by tone
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.
如果您了解原件的工作原理,您就会知道将 -1 放在哪里。
The arguments for DATEADD are DATEADD(interval, increment int, expression smalldatetime).
DATEADD 的参数是 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).
因此,在上面的表达式中,DATEDIFF 函数返回一个整数,即当前日期和日期零 (0) 之间的年差。
The expression in the above statement accepts a zero (0) as a smalldatetime.
上述语句中的表达式接受零 (0) 作为 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.
日期零是 1900 年 1 月 1 日,因此无论提供的日期是什么,都会为您提供 1 月 1 日。
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:
因此,要再回溯一年,您只需从间隔中减去 1,因此间隔变为:
DATEDIFF(yy,0,GETDATE())-1
回答by Gordon Linoff
Another method is:
另一种方法是:
select dateadd(year, -1, datename(year, getdate()) + '0101')