Monday, July 6, 2015

T-SQL Date Calculations.


  -- Yesterday
  SELECT  CAST(GETDATE()-1 AS Date) AS Yesterday
 
  -- Beginning of Year
  SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) AS StartOfYear
  -- End of Year
  SELECT CAST(DATEADD(s,-1,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) AS Date) AS EndOfYear
 
  -- Beginning of Previous Year
  SELECT DATEADD(yy, DATEDIFF(yy,0,getdate())-1, 0) AS StartOfPreviousYear
  -- End of Previous Year
  SELECT CAST(DATEADD(s,-1,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)) AS Date) AS EndOfPreviousYear

  -- Beginning of Month
  SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE()),0) StartOfMonth
  -- End of Month
  SELECT CAST(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) AS Date) EndOfMonth
 
  -- Beginning of Previous Month
  SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0) StartOfPreviousMonth
  -- End of Previous Month
  SELECT CAST(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) AS Date) EndOfPreviousMonth
 
  -- Rolling 12 Months. Begin.
  SELECT DATEADD(mm, DATEDIFF(m,0,GETDATE())-12,0) Rolling12MosBegin
  -- Rolling 12 Months End.
  SELECT CAST(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) AS Date) Rolling12MosEnd



-- Using SQL Server 2012 EOMONTH Function


-- Beginning of Year
select DATEADD(DAY,1,EOMONTH ( getdate(), - month(getdate()) )) StartOfYear
-- End of Year
select EOMONTH ( getdate(), 12 - month(getdate()) ) EndOfYear

-- Beginning of Previous Year
select DATEADD(DAY,1,EOMONTH ( getdate(), - month(getdate()) -12 )) StartOfPreviousYear
-- End of Previous Year
select EOMONTH ( getdate(),  - month(getdate()) ) EndOfPreviousYear


-- Beginning of Month
select DATEADD(DAY,1,EOMONTH ( getdate(), -1 )) StartOfMonth
-- End of Month
select EOMONTH ( getdate() ) EndOfMonth


-- Beginning of Previous Month
select DATEADD(DAY,1,EOMONTH ( getdate(), -2 )) StartOfPreviousMonth
-- End of Previous Month
select EOMONTH ( getdate(),-1 ) EndOfPreviousMonth


-- Rolling 12 Months Begin
select DATEADD(DAY,1,EOMONTH ( getdate(), -13 )) Rolling12MosBegin
-- Rolling 12 Months End

select EOMONTH ( getdate(),-1 ) Rolling12MosEnd

No comments: