上一年的上个月

时间:2014-09-15 16:05:52

标签: sql sql-server sql-server-2008

我已经能够宣布和设置抓住前几个月的数据。

DECLARE @FirstDayofPrevMonth datetime
SET @FirstDayofPrevMonth = DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)
DECLARE @LastDayofPrevMonth datetime  
SET @LastDayofPrevMonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))

我现在需要的是能够在前一个月,前一年设定和申报....

要清楚,这对我有用。我得到了2014年8月的预期结果。我期待的是2013年8月,等等。

更新: 我想我会分享另外两个我添加到我的代码中可能对其他人有帮助的部分。

我使用了以下答案并添加到其中

DECLARE @FirstDayofPrevMonth datetime
SET @FirstDayofPrevMonth = DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)
DECLARE @LastDayofPrevMonth datetime
SET @LastDayofPrevMonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))  

- 用于上一个完成的月份

DECLARE @FirstDayofPrevMonthLY datetime
SET @FirstDayofPrevMonthLY = DATEADD(year,-1,@FirstDayofPrevMonth)
DECLARE @LastDayofPrevMonthLY datetime
SET @LastDayofPrevMonthLY = DATEADD(year,-1,@LastDayofPrevMonth)

- 如果您想要当前季度的日期

,则使用此选项
DECLARE @FirstDayofCQ datetime
SET @FirstDayofCQ = DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
DECLARE @LastDayofCQ datetime
SET @LastDayofCQ =DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 1, 0)

- 这将用于前一季度

DECLARE @FirstDayofPrevQ datetime
SET @FirstDayofPrevQ = DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 1, 0)
DECLARE @LastDayofPrevQ datetime
SET @LastDayofPrevQ = DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0))

2 个答案:

答案 0 :(得分:2)

DECLARE @FirstDayofPrevMonthPriorYear datetime  
DECLARE @LastDayofPrevMonthPriorYear datetime  
SET @FirstDayofPrevMonthPriorYear = DATEADD(year,-1,@FirstDayofPrevMonth)
SET @LastDayofPrevMonthPriorYear = DATEADD(year,-1,@LastDayofPrevMonth)

答案 1 :(得分:1)

DECLARE @FirstDayofPrevMonthPrevYear datetime

SET @FirstDayofPrevMonthPrevYear = (DATEADD(yy, -1, DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)))