去年这个月的第一天和最后一天

时间:2015-04-29 16:16:14

标签: sql-server

我宣布了一些月份和日期,需要帮助才能获得去年这个月的第一个和最后一个日期。

到目前为止,我有以下内容。

DECLARE @today date Set @today = cast (getdate() as date)
DECLARE @firstdaylastmonth date Set @firstdaylastmonth = DATEADD(month, DATEDIFF(month, 0, @today)-1, 0)
DECLARE @lastdaylastmonth date SET @lastdaylastmonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@today),0))
DECLARE @lastdaythismonth date SEt @lastdaythismonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@today)+1,0)) 

-- DECLARE @firstdaythismonthlastyear SET 
-- DECLARE @lastdaythismonthlastyear SET


Select 
@today,
@firstdaylastmonth,
@lastdaylastmonth,
@lastdaythismonth

-- @firstdaythismonthlastyear
-- @lastdaythismonthlastyear

但我很难找到最后的2个声明。帮助赞赏。

2 个答案:

答案 0 :(得分:0)

您可以使用dateadd抵消12个月:

DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()
SELECT DATEADD(M,-12,CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)),@mydate),101)) ,
'Last Day of Previous Month, Last Year'
UNION
SELECT DATEADD(M,-12,CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),101)) AS Date_Value,
'First Day of Current Month, Last Year' AS Date_Type
UNION
SELECT CONVERT(VARCHAR(25),@mydate,101) AS Date_Value, 'Today' AS Date_Type
UNION
SELECT DATEADD(M,-12,CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)),101)) ,
'Last Day of Current Month, Last Year'
UNION
SELECT DATEADD(M,-12,CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))-1),DATEADD(mm,1,@mydate)),101)) ,
'First Day of Next Month, Last Year'

答案 1 :(得分:0)

我们可以CAST将当月的第一天缩短为一个日期,减去@firstdaythismonthlastyear的一年,然后从@lastdaythismonth减去一年即可获得@lastdaythismonthlastyear。< / p>

DECLARE @today date Set @today = cast (getdate() as date)
DECLARE @firstdaylastmonth date Set @firstdaylastmonth = DATEADD(month, DATEDIFF(month, 0, @today)-1, 0)
DECLARE @lastdaylastmonth date SET @lastdaylastmonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@today),0))
DECLARE @lastdaythismonth date SEt @lastdaythismonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@today)+1,0)) 

DECLARE @firstdaythismonthlastyear date SET @firstdaythismonthlastyear = DATEADD(year, -1,CAST(CONCAT(YEAR(@today),'-',MONTH(@today),'-',1) as date))
DECLARE @lastdaythismonthlastyear date SET @lastdaythismonthlastyear = DATEADD(year, -1, @lastdaythismonth)

Select 
@today,
@firstdaylastmonth,
@lastdaylastmonth,
@lastdaythismonth,
@firstdaythismonthlastyear,
@lastdaythismonthlastyear