Prior Month for Prior Year - sql

I have been able to Declare and Set grabbing the prior months data.
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))
What I now need is to be able to set and declare prior month, prior year....
to be clear, this does work for me. I get the expected result which is Aug 2014. What I'm looking to do, is get Aug 2013 and so on.
UPDATE:
I thought I would share two other pieces I added to my code that may be helpful to others.
I used the below answer and added to it
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))
-- to be used for the prior year completed month
DECLARE #FirstDayofPrevMonthLY datetime
SET #FirstDayofPrevMonthLY = DATEADD(year,-1,#FirstDayofPrevMonth)
DECLARE #LastDayofPrevMonthLY datetime
SET #LastDayofPrevMonthLY = DATEADD(year,-1,#LastDayofPrevMonth)
--This is to be used if you want for dates in the current Quarter
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)
--This is to be used for the Prior Quarter
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))

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

DECLARE #FirstDayofPrevMonthPrevYear datetime
SET #FirstDayofPrevMonthPrevYear = (DATEADD(yy, -1, DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)))

Related

Loop through the same query to build historical table changing one variable

I have read only access to SQL Server 2008 and I need to build a historical table of percentages based on different points of time in the past (i.e. the last 15 months). The only value that needs to be changed is on the *** line is -0 after GETDATE()). The value needs to change -0, -1, -2...-15. I am inserting into a temp table. Any suggestions would be appreciated.
declare #enddate datetime
declare #end1195 datetime
declare #beg1195 datetime
declare #enddos datetime
declare #begdos datetime
declare #period nvarchar(7)
***set #enddate = DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-0, -1)
set #end1195 = DATEADD(MONTH, DATEDIFF(MONTH, -1, (#enddate))-1, -1)
set #beg1195 = DATEADD(MONTH, DATEDIFF(MONTH, 0, dateadd(month, -6, #enddate)), 0)
set #enddos = DATEADD(MONTH, DATEDIFF(MONTH, -1, (#enddate))-0, -1)
set #begdos= DATEADD(MONTH, DATEDIFF(MONTH, 0, dateadd(month, -0, #enddate)), 0)
set #period = cast(MONTH(#enddate) as nvarchar(2)) + '-' + cast(YEAR(#enddate) as nvarchar(4))
--1195 BY Facilityid excluding ANES
insert into ##Fac1195
select
A.Facilityid, cast(1 as int) as Facility,
A.FSC_DESC, #period as Period, #begdos as DOS_Beg,
#enddos as DOS_End,
ROUND(sum(A.adjustments)/sum(A.charges), 2) as [1195]
from
(select
v.Facilityid, v.localfacility, v.VisitID, v.AccountNumber,
v.DOS, FSC.PrimayPayer as PayerName,
FSC.PrimaryCorpFSC as FSC_DESC,
chg.charges, isnull(adj.Adjustments,0) as Adjustments
........

How to get date to be the same day and month from one variable but in the year based on another variable?

I am trying to get the specific day of a Year.
Here's what I have tried till now:-
-- Declare few variables
DECLARE #Currentdate AS DATETIME
DECLARE #DueDate AS DATETIME
DECLARE #NewDate AS DATETIME
-- Set the variables properly, just for testing
SET #Currentdate = GETDATE()
SET #DueDate = DATEADD(MONTH, 2, DATEADD(YEAR, 1, #Currentdate))
-- Check the output
SELECT #Currentdate -- 2013-09-30 00:00:00.000
SELECT #DueDate -- 2014-11-30 00:00:00.000
So, I want to get the #NewDate based on the #Currentdate year.
For this I tried:-
SELECT #NewDate = DATEADD(DAY, DAY(DATEDIFF(day, 1, #DueDate)), DATEADD(MONTH, DATEDIFF(MONTH, 0, #Currentdate), 0))
SELECT #NewDate -- 2013-09-30 00:00:00.000
But it didn't worked. :(
My expected result is like:
-- 2013-11-30 00:00:00.000
-- Having the due date month and date same, but the year as current date one.
Any help is appreciated!
UPDATE
Sorry for all the confusion I have created. My question in simple words is:-
I want to get the a new date variable having the date and the month same as #DueDate variable but the year as given in the #Currentdate variable.
I hope that would clear things up a bit.
If the question is "given I have a particular datetime value in one variable, can I set another variable to be for the same day and month but in the current year" then the answer would be:
declare #DueDate datetime
declare #NewDate datetime
set #DueDate = '20141130'
--Need to set #NewDate to the same month and day in the current year
set #NewDate = DATEADD(year,
--Here's how you work out the offset
DATEPART(year,CURRENT_TIMESTAMP) - DATEPART(year,#DueDate),
#DueDate)
select #DueDate,#NewDate
I want to get the a new date variable having the date and the month same as #DueDate variable but the year as given in the #Currentdate variable.
Well, that's simply the above query with a single tweak:
set #NewDate = DATEADD(year,
--Here's how you work out the offset
DATEPART(year,#Currentdate) - DATEPART(year,#DueDate),
#DueDate)
Try this instead ?
DECLARE #Currentdate AS DATETIME
DECLARE #DueDate AS DATETIME
-- Set the variables properly, just for testing
SET #Currentdate = GETDATE()
SET #DueDate = DATEADD(MONTH, 2, DATEADD(YEAR, 1,
DateAdd(day, datediff(day, 0, #currentDate), 0)))
-- Check the output
SELECT #Currentdate -- 2013-09-30 18:32:35.310
SELECT #DueDate
Using DateAdd(day, datediff(day, 0, #DateTime), 0) strips off the time portion. You should also check out this SO Question/answer.
Try this one:
CAST(CAST( -- cast INT to VARCHAR and then to DATE
YEAR(GETDATE()) * 10000 + MONTH(#DueDate) * 100 + DAY(#DueDate) -- convert current year + #DueDate's month and year parts to YYYYMMDD integer representation
+ CASE -- change 29th of February to 28th if current year is a non-leap year
WHEN MONTH(#DueDate) = 2 AND DAY(#DueDate) = 29 AND ((YEAR(GETDATE()) % 4 = 0 AND YEAR(GETDATE()) % 100 <> 0) OR YEAR(GETDATE()) % 400 = 0) THEN 0
ELSE -1
END
AS VARCHAR(8)) AS DATE)

Return records of last 6 months

Below is my SQL statement
DECLARE #dStart datetime ,
#dEnd datetime
SET #dEnd = GETDATE()
SET #dStart = DATEADD(mm, -6, #dEnd)
Select * from MyTable
Where TheDate Between #dStart AND #dEnd
This will return all the records from today minus 6 months data.
But I want this months data plus only the previous 5 months data.
Currently it will return records from March as well.
Instead of
DATEADD(mm, -6, #dEnd)
You might use
dateadd(month, datediff(month, 0, #dEnd) - 5, 0)
This will truncate date to first of current month and substract five months from it.
declare #date datetime
declare #months int
declare #year int
set #months=month(GETDATE())
set #year=month(GETDATE())
set #date=getdate()
(Select * from MyTable Where TheDate Between (01/#months-5/#year) AND (01/#months/#year) ) union (Select * from MyTable Where TheDate Between (01/#months/#year) AND #date)
DECLARE #dStart datetime ,
#dEnd datetime
SET #dEnd = GETDATE()
SET #dStart = DATEADD(mm, -4, #dEnd)

SQL Get the first occurance of the 15th for a date

I need to write a function or SP that will return the first occurance of the 15th. For example, if I pass the date as May 8th, then it should return May 15th. If I pass May 30th, then it should return June 15th.
One way
DECLARE #d DATETIME
SELECT #d = '20110508'
--SELECT #d = '20110530'
SELECT CASE WHEN DAY(#d) > 15
THEN dateadd(mm, datediff(mm, 0, #d)+1, 0) + 14
ELSE dateadd(mm, datediff(mm, 0, #d)+0, 0)+ 14 end
How about;
create function udf_getNextDate(#base datetime, #day int) returns datetime as begin
set #base = case when day(#base) > #day
then dateadd(month, 1, #base)
else #base
end
return dateadd(day, -day(#base) + #day, #base)
end
select
dbo.udf_getNextDate('08 may 2011', 15),
dbo.udf_getNextDate('30 may 2011', 15),
dbo.udf_getNextDate('16 dec 2011', 15),
dbo.udf_getNextDate('01 may 2011', 15)
2011-05-15 00:00:00.000
2011-06-15 00:00:00.000
2012-01-15 00:00:00.000
2011-05-15 00:00:00.000
Just another way of doing it:
Declare #d datetime
Set #d = getdate()
Select Case
When DateDiff(Day, Day(#d), 15) < 0 then
DateAdd(month, 1, DateAdd(Day, DateDiff(Day, Day(#d), 15), #d))
Else DateAdd(Day, DateDiff(Day, Day(#d), 15), #d)
End as [Next15th]
this function may helps you
create function Get15th(#date datetime)
returns datetime
as
begin
declare #resultdate datetime
declare #y int
declare #m int
declare #d int
set #y = datepart(year,#date)
set #m = datepart(month,#date)
set #d = datepart(day,#date)
if( #d<=15)
set #resultdate =cast((str(#y)+'-'+str(#m)+'-15') as datetime)
else
set #resultdate =cast((str(#y)+'-'+str(#m+1)+'-15') as datetime)
return #resultdate
end
try
DATEADD(Day, DATEDIFF(Day, 15, Created), 0) AS CreatedDay
explained here http://improve.dk/archive/2006/12/13/sql-server-datetime-rounding-made-easy.aspx
using that link you can achive what you want
UPDATE: got it wrong ... see Dems answer
Rob's answer is close...
if you take the datediff in months, rather than days, and make your base the 15'th of a month, then add one extra month...
DATEADD(MONTH, DATEDIFF(MONTH, 14, Created) + 1, 14)
EDIT
Modified to use DATEDIFF MONTH how it works, not how I thought it should work ;)
DATEADD(MONTH, DATEDIFF(MONTH, 0, Created - 15) + 1, 14)
I usually do something like this:
declare
#date datetime ,
#target_day int
set #date = 'June 16, 2009'
set #target_day = 15
select date = #date ,
next_date = case when day(#date) <= #target_day
then dateadd(day,15-day(#date),#date)
else dateadd(day,15,dateadd(month,1,dateadd(day,-day(#date),#date)))
end
dealing with the last day of the month is a wee bit trickier, since month's have variable numbers of days, and SQL Server's date math is sometimes a wee bit baroque.

Set time portion of a datetime variable

I am working on a query that will be an automated job. It needs to find all the transactions between 8 PM and 8 PM for the last day. I was thinking of doing something like this
DECLARE #start_date DATETIME
DECLARE #end_date DATETIME
SET #start_date = DATEADD(DAY, -2, GETDATE())
SET #end_date = DATEADD(DAY, -1, GETDATE())
For an automated query this works good at figuring out the date portion. But the TIME portion of the variable is the current time that the query executes. Is there a quick simple way to hard code the time portion of both variables to be 8:00 PM?
DECLARE #start_date DATETIME
DECLARE #end_date DATETIME
SET #start_date = DATEADD(hour, 20, DATEDIFF(DAY, 2, GETDATE()))
SET #end_date = #start_date + 1
select #start_date, #end_date
This will also work:
DECLARE #start_date datetime
DECLARE #end_date datetime
SET #start_date = LEFT(CONVERT(nvarchar, DATEADD(DAY, -2, GETDATE()), 120), 11) + N'20:00:00'
SET #end_date = #start_date + 1
select #start_date, #end_date
Although cyberkiwi's answer is very clever! =)
I needed to pull a date from the database and append 3:00 Pm to it. I did it this way
select dateadd(hour, 15, datediff(day, 0, myDatabaseDate))
from dbo.myDatabaseTable
where myDatabaseId = 1
The result that it returned was 2017-10-01 15:00:00.000. The date in the database is 2017-10-01. The solution that I proposed was to keep my current date. I added 0 days to my existing date. I gave it 15:00 hours and it worked like a charm.
In case of just updating a particular part of the datetime you can use SMALLDATETIMEFROMPARTS like:
UPDATE MyTable
SET MyDate = SMALLDATETIMEFROMPARTS(YEAR(MyDate), MONTH(MyDate), DAY(MyDate), <HoursValue>, <MinutesValue>)
In other cases it may be required to copy parts of datetime to other or update only certain parts of the datetime:
UPDATE MyTable
SET MyDate = SMALLDATETIMEFROMPARTS(YEAR(MyDate), MONTH(MyDate), DAY(MyDate), DATEPART(hour, MyDate), DATEPART(minute, MyDate))
Refer SQL Server Date/Time related API references for more such functions
DECLARE #start_date DATETIME = DATEADD(HOUR, 20, DATEADD(MINUTE, 00, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))) - 2
DECLARE #end_date DATETIME = DATEADD(HOUR, 20, DATEADD(MINUTE, 00, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))) - 1
Notes:
GETDATE() + X is the equivalent of DATEADD(DAY, X, GETDATE()).
Converting a DATEIME to a DATE and then back to a DATETIME again sets the time to midnight i.e. 00:00:00.000.
Seperate SET and DECLARE statements are unnecessary, but just in case it helps later, variables may be set as part of a SELECT statement too.
I had to do something similar, create a procedure to run from a certain time the previous day to a certain time on the current day.
This is what I did to set the start date to 16:30 on the previous day, basically subtract the parts you don't want to get them back to 0 then add the value that you want it to be.
-- Set Start Date to previous day and set start time to 16:30.00.000
SET #StartDate = GetDate()
SET #StartDate = DateAdd(dd,- 1, #StartDate)
SET #StartDate = DateAdd(hh,- (DatePart(hh,#StartDate))+16, #StartDate)
SET #StartDate = DateAdd(mi,- (DatePart(mi,#StartDate))+30, #StartDate)
SET #StartDate = DateAdd(ss,- (DatePart(ss,#StartDate)), #StartDate)
SET #StartDate = DateAdd(ms,- (DatePart(ms,#StartDate)), #StartDate)
Hope this helps someone.