I have the following sql which returns the date of last monday.
SELECT DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0) //2017-05-15 00:00:00.000
However in trying to understand how this has been worked out, I'm confused
as to what the 6124 returned by the following represents
SELECT DATEDIFF(wk, 6, GETDATE())
It's only last week why is it such a high number?
Also how can the offset be a fixed number and still be able to work out the date of the previous monday
That's sunday of Jan of 1900...
SELECT
DATEDIFF(wk, '1/1/1900','5/20/2017'),
DATEDIFF(wk, '1/1/1900',GETDATE())
Specifically, they are using DATETIMEOFFSET instead of an actual DATETIME which is an acceptable parameter of DATEDIFF
So to answer you question, that's the number of weeks (since you specified wk) from the first Sunday in January 1900 to the current day.
The parameter of 6 for startdate in the datediff is just another way to reduce the output by one week, so it returns how many weeks since 1900-01-06 instead of 1900-01-01 (difference of one).
These two statements will return the same result:
select dateadd(week, datediff(week, 6, getdate()),0)
select dateadd(week, datediff(week, 0, getdate())-1,0)
Just this part: datediff(week, 6, getdate() returns the number of weeks (6,124) since 1900-01-06 which when added to a date of 1900-01-01 gives you the start of last week.
Related
I have a function that gets the first day of the previous month but I would like to understand "DATEDIFF(month, -1, getdate()) - 2" part how is it contributing in getting the first day of the previous month. The full function is given as code.
I know what dateadd and datediff functions do but I am not sure what the -1 (in the datediff function) and -2 in the dateadd function are doing.
SELECT #prev_month_first_date = DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0)
Rewriting it like this:
DATEADD(month, DATEDIFF(month, '20100101', getdate()) - 1, '20100101')
probably makes it clearer.
There's some dodgy and obscure stuff going on.
This
DATEDIFF(month, -1, getdate())
counts the month boundaries crossed between two dates, the first one is
cast(-1 as datetime) --1899-12-31 00:00:00.000
Then it subtracts 2 from that and add that many months to
cast(0 as datetime) --1900-01-01 00:00:00.000
The -1 represents the number of days from the "zero date" (1900-01-01):
SELECT CONVERT(datetime, -1);
-- 1899-12-31 0:00
It's a cryptic way to just grab a starting date to perform datediffs against, for example:
SELECT DATEDIFF(month, -1, getdate());
-- or
SELECT DATEDIFF(month, '18991231', getdate());
-- Both yield:
1431
So the expression becomes:
SELECT DATEADD(month, (1431 - 2), 0);
Which is "add 1429 months to zero date (1900-01-01)":
SELECT DATEADD(month, (1431 - 2), '19000101');
Which yields:
2019-02-01 0:00
Again 0 and -1 are just magic numbers here to represent two goalpost dates to be used in cryptic and "clever" calculations.
Personally I find such clever magic confusing and unhelpful. The beginning of the previous month can also be represented by the following expression, which is actually fewer characters and easier to follow in English (subtract two months from today (Jan 25), move to the end of that month (Jan 31), then add a day (Feb 1)):
SELECT DATEADD(DAY,1,EOMONTH(DATEADD(MONTH,-2,GETDATE())));
Just demonstrating there are many ways to skin this cat. Gordon's DATEFROMPARTS is equally valid, and I actually can't stand the EOMONTH() function, but this form allows you to only specify GETDATE() once.
I would advise you to use something like this:
select dateadd(month, -1, datefromparts(year(getdate(), month(getdate(), 1))
The intention of this is much clearer.
If I have a date value like 2010-03-01 17:34:12.018
What is the most efficient way to turn this into 2010-03-01 00:00:00.000?
As a secondary question, what is the best way to emulate Oracle's TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?
To round to the nearest whole day, there are three approaches in wide use. The first one uses datediff to find the number of days since the 0 datetime. The 0 datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;
select dateadd(d, 0, datediff(d, 0, getdate()))
The second method is text based: it truncates the text description with varchar(10), leaving only the date part:
select convert(varchar(10),getdate(),111)
The third method uses the fact that a datetime is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using floor, you get the start of the day:
select cast(floor(cast(getdate() as float)) as datetime)
To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:
select dateadd(dd, 1 - datepart(dw, getdate()), getdate())
This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with #start_of_day as a variable for readability:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, #start_of_day), #start_of_day)
The start of the year, month, hour and minute still work with the "difference since 1900" approach:
select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)
Rounding by second requires a different approach, since the number of seconds since 0 gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, #start_of_day, getdate()), #start_of_day)
To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using /5*5:
select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)
This works for quarters and half hours as well.
If you are using SQL Server 2008+, you can use the Date datatype like this:
select cast(getdate() as date)
If you still need your value to be a DateTime datatype, you can do this:
select cast(cast(getdate() as date) as datetime)
A method that should work on all versions of SQL Server is:
select cast(floor(cast(getdate() as float)) as datetime)
Try:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
UPDATE: answer on the second question:
for years you could use a little bit modified version of my answer:
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
for quarter:
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
and so on.
I checked, up to minutes - it's OK. But on seconds I've got an overflow message:
Difference of two datetime columns
caused overflow at runtime.
One more update: take a look to the following answer to the same question
This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.
declare #SomeDate datetime = '2010-03-01 17:34:12.018'
SELECT
DATEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01'
) AS CUR_DATE_FROM_PARTS
,DATETIMEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01' --DAY(#SomeDate)
,'00' --DATEPART(HOUR,#SomeDate)
,'00' --DATEPART(MINUTE,#SomeDate)
,'00' --DATEPART(SECOND,#SomeDate)
,'00' --DATEPART(MILLISECOND,#SomeDate)
) AS CUR_DATETIME_FROM_PARTS
,#SomeDate AS CUR_DATETIME
,YEAR(#SomeDate) AS CUR_YEAR
,MONTH(#SomeDate) AS CUR_MONTH
,DAY(#SomeDate) AS CUR_DAY
,DATEPART(HOUR,#SomeDate) AS CUR_HOUR
,DATEPART(MINUTE,#SomeDate) AS CUR_MINUTE
,DATEPART(SECOND,#SomeDate) AS CUR_SECOND
,DATEPART(MILLISECOND,#SomeDate) AS CUR_MILLISECOND
FROM Your_Table
Truncated Date: 2010-03-01
Truncated DateTime: 2010-03-01 00:00:00.000
DateTime: 2010-03-01 17:34:12.017
Not sure if this is the most efficient, but I like the simplicity in using the following where #SomeDate is your field.
Concat(Year(#SomeDate), '-', Month(#SomeDate), '-', '01')
If you want to truncate a date to the start of the week in a way that is independent of SET DATEFIRST you can:
--change a date backwards to nearest Monday
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN)
Breaking this down:
DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN): the dw of a known Monday (2001-01-01 was a Monday) minus the dw of your date, effectively giving the "number of days difference between your date and Monday" or "how many days back do we have to scroll your date to make it into Monday"
( ... -7)%7 - we subtract 7 from it and modulo the result by 7.
We do this because if e.g. DATEFIRST is 7 (Sunday), and your date column is Sunday then your dw is 1, and your known Monday is 2.
This means the result of the dw_for_known_monday - dw_for_your_date is +1 rather than -6
This would then mean that DATEADD will roll your date forwards to the following Monday rather than backwards to the previous Monday
If we subtract 7 off it then the result would definitely be negative, but then we wouldn't want your Mondays (which are 0 days different from the known Monday) to end up doing a DATEADD of -7, so we modulo the result by 7.
This turns any problematic -7 into 0, which means your DATEADD will only ever have a "number of days" argument between -6 and 0
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN) - we then DATEADD the (negative) number of days from the above step
If you want to roll your date backwards to e.g. a Sunday, change the date 2001-01-01 to a date that is a known Sunday (like 2000-12-31), etc
select datediff(mm, 0, getdate())
This function returns the output as 1376. I dont understand on how this has been calculated
select dateadd(mm, datediff(mm, 0, getdate()), -1)
This function returns the output as "2014-08-31 00:00:00.000" which is Aug-31st.
My understanding according to dateadd() - mm stands for month.
select dateadd(mm, datediff(mm, 0, getdate()), -2)
The output is "2014-08-30 00:00:00.000".
Which is again confusing for me as this was supposed to negate the month by -1. But instead, it is doing it by day difference.
mm is month, but you should use "month". It is then obvious what you are doing.
The statement:
select datediff(month, 0, getdate())
is getting the number of months since date is 0. SQL Server stores dates as the number of days since Jan 1, 1900. So, this base date is 1,376 months in the past (as I write this).
When you write:
select dateadd(month, datediff(month, 0, getdate()), -1)
Then you are adding the number of months since 1900-01-01 to the date with the value -1. The -1 is interpreted as a datetime, which corresponds to 1899-12-31. Hence, when you add the months you are getting the last day of the previous month. When you change -1 to -2, you get the second to last day, because you are counting from 1899-12-30.
I used a query that somebody here on SO provided me with to get the results from the before currentdate, which works perfectly:
WHERE IssuedOn >= DATEDIFF(D, 1, GETDATE()) and IssuedOn < DATEDIFF(D, 0, GETDATE()) ";
I though that for the previous month, changing D for M will be enough but obviously I am missing something:
WHERE IssuedOn >= DATEDIFF(M, 1, GETDATE()) and IssuedOn < DATEDIFF(M, 0, GETDATE()) ";
This does not work. I need to return rows where IssuedOn is from previous month from current date.
The short answer:
The following SQL will get the values for your date range:
-- The beginning of the current month
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
-- The beginning of the previous month
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
-- The beginning of the next month
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())+1, 0)
You can replace MONTH with any other datepart value to get date ranges for things like years, hours, days, etc...
The long answer:
The reason your days query worked but your months query did not is that SQL Server stores DATETIME objects as FLOATs. The integer portion representing the date as days since 1900-01-01 00:00:00.000 (hereafter referred to as "0"). The decimal portion representing the time (as a percentage of 24 hours).
If you call DATEDIFF(DAY, 0, GETDATE()), it will get the number of days since "0", which basically is the same as converting the FLOAT representation of GETDATE() to an INTEGER representation (truncating the minutes and leaving you at 00:00). For instance, if I run SELECT CAST(GETDATE() AS FLOAT) today, I get "41675.3452306327". If I run SELECT DATEDIFF(DAY, 0, GETDATE()), I get "41675".
If you call DATEDIFF(MONTH, 0, GETDATE()), you will get the number of months since "0". Today, this gives me "1369". If you try to compare that value to a DATETIME, it will simply convert "1369" to a DATETIME, treating it as "1369 days since 0" and result in a DATETIME of "1903-10-02 00:00:00.000". To see this for yourself, try: SELECT CAST(DATEDIFF(MONTH, 0, GETDATE()) AS DATETIME).
If you want to trim the days (and time-stamp) out of a DATETIME, you need to take the results of your DATEDIFF query and add it back to "0" with the DATEDIFF function, like so:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
This basically takes date (to the month) and figures out how many months have passed since "0", then adds that number of months to "0". In short, it returns a DATETIME that represents the beginning of the current month.
If you want to get the previous or next month, you can simply decrement or increment the value returned by the DATEDIFF function before passing it into the call to DATEADD, like so:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())+1, 0) -- Get the next month
I am currently getting first day Of this week and last week values with vbscript function in 2/12/2009 format. I was wondering if it was possible with SQL query.
These statements should do what you want in TSQL. Note, the statements are based on the current date. You can replace getdate() for whatever date you wish:
Select dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) as LastWeekStart
Select dateadd(wk, datediff(wk, 0, getdate()), 0) as ThisWeekStart
Select dateadd(wk, datediff(wk, 0, getdate()) + 1, 0) as NextWeekStart
There are lots of other date routines here.
Ben's answer gives the wrong answer if today is Sunday. Regardless of whether the first day of the week is Sunday or Monday, the current date should be included in the current week. When I run his code for 3/24/2013, it gives me a ThisWeekStart of 3/25/2013. I used the following code instead:
SELECT DATEADD(DAY, 1 - DATEPART(DW, '3/24/2013'), '3/24/2013')
Get the first day of current week.
for extra information use this link.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_dayofweek
select date(curdate()-DAYOFWEEK(curdate()-1)) as dat;