Sql date difference query - sql

I need to take diffrence of two dates which are columns in my table:
LastAIResponseReceivedDate,LastUploadedDate
I am Using this statement:
update Group set AITime=(CONVERT (varchar,(LastAIResponseReceivedDate-LastUploadedDate),121)) where GroupId=2 and Id=5
I am getting the time diffrence correctly but my date diffrence is wrong 1900-01-01 01:56:56.427
How to get the date diffrence correctly

Do not understand in your question, that what type of difference you want (Day, month, year).
But this may help you.
SELECT DATEDIFF(month, 'Start_date_variable', 'End_date_variable') AS DateDiff;
Syntax As:
DATEDIFF(interval, date1, date2)
Interval can be anything like day, month, year, week, hours, second etc..

Parse to datetime first, you need
Set timediff = DATEDIFF(s, LastAIResponseReceivedDate,LastUploadedDate)
Save time difference as second is more convenient for later use. If you want to save in some date format, remember not datetime, time difference is not a 'datetime'.
So,
Select CONVERT(varchar, FLOOR(timediff/(3600*24))) + 'D ' + CONVERT(varchar, DATEADD(s, timediff, 0), 114)

Related

Is there a quick way to separate date and time from a time stamp in sql?

I am using sql to calculate the average daily temperature and max daily temperature based on a date timestamp in an existing database. Is there a quick way to accomplish this?
I am using dBeaver to do all my data calculations and the following code is what I have used so far:
SELECT
convert(varchar, OBS_TIME_LOCAL , 100) AS datepart,
convert(varchar, OBS_TIME_LOCAL, 108) AS timepart,
CAST (datepart AS date) date_local,
CAST (timepart AS time) time_local
FROM
APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER;
The data format as follows:
ID time_stamp temp
--------------------------------------------
de2145 2018-07-16 16:55 103
There are multiple IDs with 24hrs of temperature data at 1 min increments.
I am not sure if I understand what you need but I will try:
Your question: "Is there a quick way to separate date and time from a time stamp in sql?"
Answer:
select to_char(datec, 'hh24:mi')
, to_char(datec, 'yyyy-mm-dd')
from test;
Use to_char with format to select date part and time part.
You seem to want aggregation:
SELECT convert(date, OBS_TIME_LOCAL) AS datepart,
avg(temp), max(temp)
FROM APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER
GROUP BY convert(date, OBS_TIME_LOCAL);

How to compare current time to retrieve record stored in SQL

I have a database in which one of the column name is 'date' I need to count the number of entries that have been added with today's date after 09.00.00
So far I have done this..I am wondering where do I specify the time '09.00.00'
SELECT COUNT(*) AS total from DATABASENAME
WHERE date >= Convert(datetime, Convert(int, GetDate()))
Here's code that should work. You're essentially converting a datetime to a date to remove the time, then back to a datetime and adding in the hour that you want.
SELECT COUNT(*) AS Total
FROM TableName
WHERE Date >= DATEADD(HOUR, 9, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))
Well is the date column store date and time or date only, if it is date only you need to add the time also in the column and also avoid converting data type in where condition try the above query with a parameter variable

SQL - Query condition for future date time

Im having trouble with this query. I want to not select records that have passed the SYSTIME for the current date but display records for future dates even if they have passed the current SYSTIME
SELECT *
FROM TABLE
WHERE DATE>= CONVERT(date, SYSDATETIME())
AND STARTTIME > CONVERT(time, SYSDATETIME())
This is the query. I know why it doesnt work but I can't think of a way to do what I stated above.
SELECT *
FROM TABLE
WHERE
(
(DATE = CONVERT(date, SYSDATETIME()
AND STARTTIME > CONVERT(time, SYSDATETIME()
)
OR Date > sysdatetime()
)
You need an or condition since date time are in different fields you must first resolve today's date and time and then all future dates regardless of time.
This depends a lot on what the original data types are. Let's assume they are date, time, or datetime.
If you want anything in the future, then this works:
where [date] + starttime > sysdatetime()
If you want just future dates then try:
where [date] > cast(sysdatetime() as date)
The latter is how I interpret your question, but I'm not 100% sure that my interpretation is correct.

Easier way to compare a DATE field to the date value of GETDATE?

I have a field in a table Event.EventDate and it's of the data type DATE rather than DATETIME and then I have a view that has the following WHERE clause:
WHERE e.EventDate >= CAST(CONVERT(VARCHAR(MAX), GETDATE(), 101) AS DATETIME)
As you can see, I'm just trying to get all events >= today's date. The above code works, but it's ugly. I tried this ...
WHERE e.EventDate >= CONVERT(VARCHAR(MAX), GETDATE(), 101)
... and this ...
WHERE e.EventDate >= CONVERT(DATETIME, GETDATE(), 101)
... but those didn't work, they gave me every event > today's date. However, even if the above worked, it's still ugly.
Isn't there a better way?
Try:
WHERE e.EventDate >= cast(getdate() as date)
To cast getdate() into a date time. It's a clean way in SQL Server 2008 and up to strip out the time portion of a datetime type.
Using Shan Plourde's method is certainly cleaner and quicker, but for the more general case when you want to round a datetime to a particular time interval, I use
dateadd(dd,datediff(dd,0,[datetime column]),0)
where dd stands for day, and can be replaced with mm (month), hh (hour), mi (minute), and probably others.
If you want to get fancy and round to, say, 15 minute intervals, you can use
dateadd(mi,
-datepart(mi,[datetime column])%15,
dateadd(mi,datediff(mi,0,[datetime column]),0)
)
where % is the modulo operator. You'll get wacky results for this if you don't use an interval that divides 60 evenly.

DATEDIFF Getting the previous month

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