How to get one month ago from today in SQL Server 2008? - sql-server

I´m writing a query where i get the last month, but with the time in zeros (if today is 2013-05-21 then i want to get 2013-04-21 00:00:00.000).
So I tried:
select (dateadd(month,datediff(month,(0),getdate())-1,(0)));
But I get the first day of the previous month.
Then I tried:
select dateadd(month, -1, GETDATE());
I get the right day, but I also get the current time (2013-04-21 11:41:31.090), and I want the time in zeros.
So how should my query be in order to get something like: 2013-04-21 00:00:00.000
Thanks in advance.

In SQL Server 2008 there is the date data type, which has no time attached. You can thus remove the time portion quite easily simply by converting, then performing the DateAdd.
SELECT DateAdd(month, -1, Convert(date, GetDate()));
This will return a date data type. To force it to be datetime again, you can simply add one more Convert:
SELECT Convert(datetime, DateAdd(month, -1, Convert(date, GetDate())));
You may not need the explicit conversion to datetime, though.
Note: "One month ago from today" could be defined in many different ways. The way it works in SQL server is to return the day from the previous month that is the closest to the same day number as the current month. This means that the result of this expression when run on March 31 will be February 28. So, you may not get expected results in certain scenarios if you don't think clearly about the ramifications of this, such as if you performed the one-month calculation multiple times, expecting to get the same day in a different month (such as doing March -> February -> January).
See a live demo at SQL Fiddle
The demo shows the values and resulting data types of each expression.

Try like this..
select Cast(Cast(dateadd(month, -1, GETDATE()) as Date) as Datetime);

You can use this , it's pretty simple and worked for me -
SELECT SUM( amount ) AS total FROM expenses WHERE MONTH( date ) = MONTH( curdate() ) -1

To get the previous month start date and end date
DECLARE #StartDate date;
DECLARE #EndDate date;
select #StartDate= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
select #EndDate= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)

Here are many common dates you may need to pull with logic
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0) -- Today Midnight
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),-1) -- Yesterday Midnight
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)) -- First of Last Month
SELECT DATEADD(d,DATEPART(DD,GETDATE()-1),DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)) -- Same Day Last Month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) -- Last of Last Month
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) -- First of this month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- Last of this month
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- First of next month
SELECT DATEADD(d,DATEPART(DD,GETDATE()-1),DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- Same Day Next Month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)) -- Last of next month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+12,0)) -- Last of prior month one year from now
SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(DAY, 13-(##DATEFIRST + (DATEPART(WEEKDAY,GETDATE()) %7)), GETDATE())),0) -- Next Friday Midnight

Related

Is there a convenient way to compare week-over-week data in SQL?

I have a table full of daily aggregate data, but I occasionally need to pull weekly aggregate data, and provide info on increases or decreases. For that reason, I was considering using T-SQL DATEPART functionality to get week-number and year info for dates.
For example, I can get the following info using today's date (9/11/2020):
#nowWeekNumber int = datepart(wk,#today), --yields 37
#nowYear int = datepart(year,#today), --yields 2020
Using that logic, I could then gather info on records where year is 2020 and weekNumber is 36, and then I could compare those numbers to get a weekly increase/decrease. (Or maybe I'd compare weeks 35 and 36 to ensure that I'm dealing w/ entire weeks, but you get the picture)
However, if the date is 2021-01-03, that's going to return a year of 2021, and a weekNumber of 2. If I subtract a week, I'm going to get year 2021 and weekNumber 1. That weekNumber is only going to contain January 1st and 2nd, because 12/27 thru 12/31 are considered year 2020 and weekNumber 53 (even though the calendar week is 12/27 thru 1/2).
In other words, I don't think I can use weekNumber to gather weekly data, even though that would be fairly convenient. I'm aware that I can use DATEADD functions to grab the start and end-date for consecutive weeks, and I can then gather aggregate data for records BETWEEN those dates, but is there a more-convenient way to do this?
Why don't you consider using dateDiff as key function? As...
select dateDiff(wk, 0, getDate())
Returns a single integer for the whole week (6297 for '20200911') and :
select dateAdd(wk, dateDiff(wk, 0, getDate()), 0),
dateAdd(dd, 6, dateAdd(wk, dateDiff(wk, 0, getDate()), 0))
or
select dateAdd(wk, 6297, 0),
dateAdd(dd, 6, dateAdd(wk, 6297, 0))
gives you the 1st and last day of that week.
You can use DATEPART but instead of wk you can use the iso week. Then you don't have the problem with a week being split in 2. To be sure also use SET DATEFIRST to define exactly on which day the week starts.
SET DATEFIRST 1; --use monday as first day of the week
SELECT datepart(iso_week,'2021-01-01');
SELECT datepart(iso_week,'2021-01-03');
SELECT datepart(iso_week,'2021-01-04');
The other option is to create your own calendar table and join that to your daily table.
EDIT: for a week start on sunday
SET DATEFIRST 7;
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2020-12-27'),'2020-12-27' ) )
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2020-12-28'),'2020-12-28' ) )
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2021-01-01'),'2021-01-01' ) )
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2021-01-02'),'2021-01-02' ) )

Return dates from last/this week depending on the current time and when "production" started

Sorry if the Title is confusing but it's hard to explain what I'm after in one phrase.
I'm currently producing a report based on the production for the week. I start off my CTE construction with the following to get the days Monday to Friday of the current week:
WITH
cte_Date AS
(
SELECT
CAST(DateTime AS date) AS Date
FROM
( VALUES
(GETDATE()
)
, (DATEADD(day,-1,GETDATE()))
, (DATEADD(day,-2,GETDATE()))
, (DATEADD(day,-3,GETDATE()))
, (DATEADD(day,-4,GETDATE()))
, (DATEADD(day,-5,GETDATE()))
, (DATEADD(day,-6,GETDATE())) ) AS LastSevenDays(DateTime)
WHERE
DATENAME(weekday, DateTime) = 'Monday'
UNION ALL
SELECT
DATEADD(day,1,Date)
FROM
cte_Date
WHERE
DATENAME(weekday,Date) <> 'Friday'
)
This is working fine. I have made the report available to users so they can run it anytime however sometimes nobody is available to run it last thing Friday. This means they don't get to see the full production for Friday and then the following week the CTE days change.
I'm trying to keep this a one-click affair so rather than introduce date parameters I proposed to the users that we adjust the query such that if they run the report before midday on "Monday" then it will show them last week's figures and they were happy with this (me and my big mouth). I put Monday in quotes because what we really mean of course is the first production day of the week.
My primary data table (which we'll call MyData) has a datetime field named DateTime (really!) that I can reference to determine the first day of production for the week.
One final caveat: Due to the layout of the report the users insisted that they always want to see the five days Monday to Friday, even if there is no production on a given day. (Consequently I do a LEFT JOIN from cte_Date to all other tables required.) So to be clear, right now as I'm typing this it's 11:45am local time on Tuesday and yesterday happened to be a public holiday here so running the report now should return Monday to Friday last week, but running it in 20 minutes time should return Monday to Friday this week.
Please help, my poor brain is getting twisted trying to figure it out.
There are a few different ways you can tackle this, but they all boil down to the same thing: you need a way of figuring out whether it's before or after 12pm on the first working day of the current week, then you need to get the Monday of the current "production week".
Let's just say, for simplicity's sake, you have some sort of table that contains public holidays (or non-production days). To find out whether it's the first day of the current production week, you basically just have to add the number of days in a row since the start of the week that have been public holidays.
Then you need to figure out whether it's before or after 12pm of that day.
If it's before you want last week's Monday-Friday. If it's after, you want this week's Monday-Friday.
Here's one way you might do this:
DECLARE #NonProductionDays TABLE (NPD DATE UNIQUE NOT NULL); -- Public holiday table.
INSERT #NonProductionDays (NPD) VALUES ('2017-09-25');
DECLARE #i INT = -- You don't need a variable for this, but just to keep things simple...
(
SELECT COUNT(*) -- Extract number of public holidays in a row this week before current date.
FROM #NonProductionDays AS N
WHERE DATEDIFF(WEEK, 0, N.NPD) = DATEDIFF(WEEK, 0, GETDATE())
AND N.NPD <= GETDATE()
AND (DATENAME(WEEKDAY, N.NPD) = 'Monday' OR EXISTS (SELECT 1 FROM #NonProductionDays AS N2 WHERE N2.NPD = DATEADD(DAY, -1, N.NPD)))
);
SELECT D = CAST(DATEADD(DAY, T.N, DATEADD(WEEK, DATEDIFF(HOUR, DATEADD(DAY, #i, '1900-01-01 12:00:00'), GETDATE()) / 24 / 7, '1900-01-01')) AS DATE)
FROM (VALUES (0), (1), (2), (3), (4)) AS T(N);
/*
Breaking this down:
X = DATEADD(DAY, #i, '1900-01-01 12:00:00')
-- Adds the number of NPD days this week to '1900-01-01 12:00:00'
-- So, for example, X would be '1900-01-02 12:00:00' this week
Y = DATEDIFF(HOUR, X, GETDATE()) / 24 / 7
-- The number of weeks between X and now, by taking the number of hours and dividing by 24 then by 7
-- The division is necessary to compare the hour.
-- So, for example, as of 11am on the September 26 2017, you'd get 6142.
-- As of 12pm on September 26 2017, you'd get 6143.
Z = DATEADD(WEEK, Y, '1900-01-01')
-- Just adds Y weeks to 1900-01-01, which was a Monday. This tells you the Monday of the current "production week".
-- So, for example, as of 11am on September 26 2017, you'd get '2017-09-18 00:00:00.000'.
-- As of 12pm on September 26 2017, you'd get '2017-09-25 00:00:00.000'.
Then we cast this as a date and add 0/1/2/3/4 days to it to get Monday, Tuesday, Wednesday, Thursday and Friday of the current "production week".
*/
I'm not sure I came up with the most efficient approach, but after a week of tossing it about in my brain this is what I came up with. I approached the problem from the opposite direction of that suggested by #ZLK.
My existing logic was already giving me the Monday of this week so in a subquery I looked for the first production record after Monday, stripped off the time with a DATEDIFF and made it midday with a DATEADD. I was then able to compare the current Date/Time with midday of the first production day to determine whether to reduce the date by one week.
I replaced this SELECT clause:
SELECT
CAST(DateTime AS date) AS Date
with this one:
SELECT -- Monday this week if it's after midday on the first production day otherwise Monday last week
DATEADD(week,IIF(GETDATE()>=DATEADD(hour,12,(
SELECT DATEDIFF(day,0,MIN(DateTime))
FROM MyData
WHERE CAST(MyData.DateTime AS date) >= CAST(LastSevenDays.DateTime AS date)
)),0,-1),CAST(LastSevenDays.DateTime AS date)) AS Date
To cater for the case where a new week has commenced but the operator runs the report before production starts I carefully arranged the boolean condition inside my IIF clause so that the empty result set from the subquery would mean the test returned FALSE and the operator would still see last week's figures.
(#ZLK, Thanks for your input - you did help my thinking a bit but I don't think your answer should be marked as correct. What I've come up with here is what I was originally requesting and didn't require the use of a static table.)

Date filter on column in sql

I have query that filtered by date, for now it take only the last 24h from the moment I execute it, for doing that I'm using the next code:
( DateDiff(HH, vw_public_task.complete_date, getdate()) < 25)
There is a way that my date filter will give query results for the last 24h but not depending on my current hour but according to "day 08:00am" -- "day+1 08:00am" at any time that I execute it?.
For example if I execute my query now I want to see date results from yesterday 08:00am till today 08:00am.
You can calculate yesterday 8am using the formula:
-- Yesterday at 8 am.
SELECT
DATEADD(HOUR, 8, CAST(CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS DATETIME)) AS Yesterday8AM
;
GetDate returns the current date. The innermost date add subtracts one day. Casting this as a date removes the timestamp. Casting this back to a DateTime gives yesterday at midnight. Now we are dealing with a DateTime we can use date add, again, to add 8 hours.
If you are using SQL Server 2012, or above, consider the native function DATETIME2FROMPARTS instead.
Use Date() (How to part DATE and TIME from DATETIME in MySQL).
( DateDiff(HH, vw_public_task.complete_date, Date(getdate())+8 ) < 25)

How to add days to the current date?

I am trying to add days to the current date and it's working fine but when I add 360 days to the current date it gives me wrong value.
eg: Current Date is 11/04/2014
And I am adding 360 Days to it, it should give me 11/04/2015, but it is showing the same date 11/04/2014. the year is not changing.
Here is my code:
select dateadd(dd,360,getdate())
Just do-
Select (Getdate()+360) As MyDate
There is no need to use dateadd function for adding or subtracting days from a given date. For adding years, months, hours you need the dateadd function.
select dateadd(dd,360,getdate()) will give you correct date as shown below:
2017-09-30 15:40:37.260
I just ran the query and checked:
Dateadd(datepart,number,date)
You should use it like this:
select DATEADD(day,360,getdate())
Then you will find the same date but different year.
From the SQL Server 2017 official documentation:
SELECT DATEADD(day, 360, GETDATE());
If you would like to remove the time part of the GETDATE function, you can do:
SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
can try this
select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result
Two or three ways (depends what you want), say we are at Current Date is
(in tsql code) -
DECLARE #myCurrentDate datetime = '11Apr2014 10:02:25 AM'
(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)
SELECT #myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.
SELECT DateADD(DAY, 365, #myCurrentDate) or DateADD(dd, 365, #myCurrentDate)
will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE #myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).
So what I think you meant was
SELECT DateADD(year, 1, #myCurrentDate)
which gives 2015-04-11 10:02:25.000.
or better yet
SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, #myCurrentDate), 0))
which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?
This will give total number of days including today in the current month.
select day(getDate())
Add Days in Date in SQL
DECLARE #NEWDOB DATE=null
SET #NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)
SELECT DateAdd(5,day(getdate()) this is for adding 5 days to current days.
for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query

Get the date one month before and it's always the last day of the month

In my db, I have a column, 'Transaction Date' with datetime datatype. For instance, '2011-05-31 00:00:00.000'.
I would like to create a SQL Query by selecting data with whereby the 'Transaction Date' column date is one month before the #InputDate.
I have tried with...
DATEADD(MONTH,-1,#InputDate) and it returns '30-May-2011', which is not what i want!
I want the value returns will always be the last day of the month like '31-May-2011'
Use the following scripts:
Last Day of Previous Month:
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) LastDay_PreviousMonth
Last Day of Current Month:
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) LastDay_CurrentMonth
Last Day of Next Month:
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)) LastDay_NextMonth
Last Day of Any Month and Year:
DECLARE #dtDate DATETIME
SET #dtDate = '8/18/2007'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#dtDate)+1,0))
LastDay_AnyMonth
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
GETDATE() can be replaced by your input date
Last day of same month
SELECT DATEADD(m, DATEDIFF(m, -1, '2011-05-31'), -1)
Last day of last month
SELECT DATEADD(m, DATEDIFF(m, 0, '2011-05-31'), -1)
I think you're asking, given any date, for the last day of the previous month?
If so, the following works (where CURRENT_TIMESTAMP is being used as the date to search from, '20010101' and '20001231' are constants):
select DATEADD(month,DATEDIFF(month,'20010101',CURRENT_TIMESTAMP),'20001231')
It works because the relationship between the two constant dates is that, compared to '20010101', '20001231' was the last date of the month before.
Since SQL Server 2012 you can use the EOMONTH built-in function to get the last day of a month.
So, to get the last day of the previous month you can use this query:
SELECT EOMONTH(GETDATE(), -1)
Where instead of GETDATE() you can put your Date var.
SELECT EOMONTH(#InputDate, -1)

Resources