I am a complete noob to SQL and trying to understand why this query returns "115":
select datediff(yy, -3, getdate())
datediff takes three Parameter. The first is the interval, the second the start date and the third the end date. You are passing -3 as start date, there we can show:
SELECT CAST(-3 AS datetime) -- results in '1899-12-29 00:00:00.000'
And because 2014 - 1899 is 115, you will get this as result.
Because DATEDIFF() calculates an interval between 2 dates, and you specified year -3 in one of them.
Firstly, the date "zero" is 12/30/1899 on SQL server.
Secondly, your "-3" was an incorrect date format and it thus replaced it with its 0
2014 - 1899 = 115
Use DATEADD() instead to achieve what you want to do.
DateDiff gives difference in years/date/months etc based on what you have given in first parameter. second and third parameter are datetime values which will be used to calculate the difference i.e. (param2 datetime value - param3 datetime value).
Now in your case param2 is "-3"
run this queries in you ms sql and observe the outputs :
select CAST(-3 as datetime)
select GETDATE()
select datediff(yy, -3, getdate())
Related
I would like to differentiate between two dates and round the result to the next day.
For exemple, if I have date1='2020-03-10 11:59:00' and date2='2020-03-10 20:53:00', the difference between date1 and date2 with datediff() is equal to 8 hours. I would like to round this result to have 24 hours.
EDIT
I tried by using dateadd() like this :
select DATEADD(HOUR, DATEDIFF(HOUR, '2020-03-10 11:59:00', '2020-03-10 20:53:00'),0)
Return 1900-01-02 09:00:00.000 doesn't correspond to what I want.
The explanation of the output is not at all clear so I am just guessing here. I am taking the difference in days between two dates. Then adding 1 because if two dates are the same day the difference in days is 0. Then multiplying that result by 24. I changed up the date literal so it is ANSI compliant and will always get the correct date regardless of localization or language settings.
declare #date1 datetime = '20201003 11:59:00'
, #date2 datetime = '20201003 20:53:00'
select datediff(day, #date1, #date2) + 1 * 24
I need to run a SQL script every night that extracts data from the previous 2 days. For example: On July 9 at 1am, the script runs and needs to extract data from July 8 and July 7. On July 10 at 1am, it needs to extract data from July 9 and July 8, etc.
The script is functional, in that it correctly extracts data for a fixed date range (by including the actual date range in the script), but I don't know how to make it do the "2 days prior" part.
Figuring this out is beyond me! Can anyone provide guidance?
Using SQL Server 2014
You can do:
where datecol >= convert(date, dateadd(day, -2, getdate())) and
datecol < convert(date, getdate())
That said, I would be very wary about putting this logic directly into a query. I would create a stored procedure in SQL Server and have it take #fromdate and #todate arguments.
Then, schedule a job that does the above calculation and calls the stored procedure with the right parameters.
One day, when the server is down or the logic fails, you will appreciate having the flexibility to specify the date range yourself.
I would create three variables.
#today: is the current datetime cast to a date to set it to midnight
#startDate: first/start date where I would use the DATEADD function to subtract two days
#endDate: end date that you can subtract 1 second from today
This should get you a date range of 2019-07-07 00:00:00.000 to 2019-07-08 23:59:59.000
DECLARE #today DATETIME = CAST(GETDATE() AS DATE);
DECLARE #startDate DATETIME = DATEADD(DAY, -2, #today);
DECLARE #endDate DATETIME = DATEADD(SECOND, -1, #today);
Time is usually very critical when working with dates, make sure your start date starts at the beginning of the day and your end date ends at the very end of the day!
Your query would then look like:
SELECT *
FROM my_table
WHERE my_date_column BETWEEN #startDate AND #endDate
Hi I am trying to get (current Datetime - Years).
Below is my Query..
print getdate()
print (getdate()-(365.25*7))
Result:
Dec 30 2013 10:47AM
Dec 30 2006 4:52PM
is giving correct result.
But When i try
print getdate()
print (getdate()-year(7))
Result:
Dec 30 2013 10:52AM
Oct 17 2008 10:52AM
Can anyone please tell what is wrong in it?
Rather use DATEADD with the datepart set to YEAR.
Returns a specified date with the specified number interval (signed
integer) added to a specified datepart of that date.
Something like
SELECT GETDATE() Today, DATEADD(YEAR,-7,GETDATE()) Today7YearsAgo
SQL Fiddle DEMO
The year(7) part return 1900, which is the year part of 1900-01-08 00:00:00.000 (CAST(7 AS DATETIME)). Then getdate()-year(7) equates to getdate()-1900, which is a day subtraction.
Try this
print getdate()
print DATEADD(Year, -7, GETDATE())
DATE ADD() Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
print getdate()
print DATEADD(Year, -7, GETDATE())
Try MSSQL DATEADD function
select DATEADD(Year,-7,GETDATE());
I've referred to this on MSDN but I'm still unsure what the second argument in the DATEDIFF function is doing in the following two examples:
SELECT DATEDIFF(yy,0,getdate()) --run on 14 Aug this returns 112
SELECT DATEDIFF(yy,1000,getdate()) --I chose 1000 arbitrarily and run on 14 Aug this returns 110
Usually I'll use DATEDIFF to find the number of days, or number of years between two months and the second argument is then a date.
Reason I'd like to understand the above is to ultimately understand the following:
SELECT DATEADD(yy, DATEDIFF(yy,0,GETDATE()), 0)
If you use an integer as the second argument (or for any datetime/smalldatetime assignment for that matter), this is interpreted as the number of days since 1900-01-01.
DECLARE #d1 DATETIME = 0, #d2 DATETIME = 1;
SELECT #d1, #d2;
Result:
1900-01-01 00:00:00.000 1900-01-02 00:00:00.000
Note that this doesn't work for new data types like DATE during direct assignment:
DECLARE #d DATE = 0;
Result:
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date
But it can still work using date math, e.g.:
DECLARE #d DATE = DATEADD(YEAR, 0, SYSDATETIME());
SELECT #d;
Result:
2012-08-14
For these inconsistent reasons, I recommend you use proper date literals so that it is clear which date you mean and so that it works regardless of the data type. This is a habit I find hard to break, since typing 0 is so much easier than 19000101...
Consider below example to understand this concept better. 0 is default date "1900-01-01"
Below Query gives output as 2017-10-31 00:00:00.000
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0))
Dividing the above query into various parts to understand the calculation.
-- 1414 Months since '1900-01-01'
SELECT DATEDIFF(MONTH,0,SYSDATETIME()) + 3
-- adding 1414 Months to Default date 1900 Produces '2017-11-01 00:00:00.000'
SELECT DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0)
--Subtract 1 day from '2017-11-01 00:00:00:000' gives last day of previous month.
SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0))
The second argument to datediff() is a date.
The first example returns the "start" date of time in the SQL Server world. That would be 112 years before the current date.
The second example is rather non-sensical. As implemented, the dates are represented as number days since the earliest date. This is the number of years since 1000 days after the earliest date.
The last example adds a number of years to the base date. It then adds a number of months. Since the base date is 1/1/1900, this is giving you the first date of the day after the nth month in the yth year.
I want to get the previous month relative to the current date
SELECT datediff(mm,-1,2-2-2011)
This query gives 67 which is a wrong value .. where i went wrong ?
You can use DATEADD
eg.
SELECT DATEADD(month, -1, GETDATE())
This 2-2-2011 is not a valid date literal - you are subtracting 2 from 2 and then 2011 from the result - proper date literals are '2-2-2011' and #2-2-2011#. You can use GETDATE() to get the current date, instead of relying on a literal.
Nor should you be using DATEDIFF - it gives you the difference between dates.
You should be using DATEADD to calculate new dates.
Try this:
SELECT DATEADD(mm,-1, GETDATE())
This will get the date a month ago.
If you just want the month, you need to also use DATEPART:
SELECT DATEPART(mm, SELECT DATEADD(mm,-1, GETDATE()))
SELECT datepart(mm, dateadd(mm,-1,'2011/1/1') )
If you want the month before the current month, you want
SELECT MONTH(DATEADD(mm, -1, GETDATE()))
If you want the date for a month before the current date, you want
SELECT DATEADD(mm, -1, GETDATE())
BTW, SELECT datediff(mm,-1,2-2-2011) computes the number of months between day -1 and day -2011, which is 67 (2010 / 30). That's nowhere near what you seem to actually want.
You need to use DATEADD - not DATEDIFF
DATEDIFF calculates the difference between two dates - it doesn't add day or months to an existing date....
Also, you need to put your dates into single quotes: use '2-2-2011' instead of simply 2-2-2011.
And lastly: I would strongly recommend using the ISO-8601 date format YYYYMMDD (here: 20110202) - it will work regardless of the language and regional settings on your SQL Server - your date format will BREAK on many servers due to language settings.
DATEDIFF calculates the difference between your stating and ending dates
every date previous to the current date has a positive number and every date next to the current date has negative number, this works in geting your specific date weather it a day,month,year or hour to understand this better below is the syntax of datediff
DATEDIFF (your datetime type, your starting date,your ending date)
the function does (your ending date)-(your starting date)
in your case the below datediff will work just pefectly
SELECT DATEDIFF (month,[you_date_or_datetime_column],GETDATE()) = 1
You can use DATEADD try this code
For previous month
SELECT DATEADD(month, -1, GETDATE())
For 7 day previous
$date = date('Y-m-d',strtotime("-7 days"));
SELECT * FROM users WHERE `date` LIKE '%$date%'
$date varibale get previous date date