How to compare datetime in SQL Server? - sql

I have to show the date 2018/01/30 if the datetime is between 2018/01/30 04:59:59.000 and 2018/01/31 04:59:59.000
I have a table called DataEntry. I want to move those records by date as per my criteria.
This DataEntry table have TransferTime that datatype is datetime.
As per my criteria if the TransferTime is 2018/01/30 01:30:59.000 then the date should be 2018/01/29

I think you can simply just write like this:
select
case when DATEPART(HOUR,'2018/01/30 01:30:59.000') >= 05 then cast('2018/01/30 01:30:59.000' as date)
else cast(dateadd(Dd,-1,'2018/01/30 01:30:59.000' )as date)
end

This is somewhat of a guess on vague logic, but perhaps using CONVERT and DATEADD?
WITH VTE AS(
SELECT CONVERT(datetime2(3),DT) AS DT
FROM (VALUES('20180130 04:59:59.000'),('20180131 01:00:34.000'),('20180130 01:30:59.000')) V(DT))
SELECT CONVERT(date, DATEADD(SECOND, -17999,DT)) AS D, DT
FROM VTE;
It's worth noting that you, oddly, state that '20180130 04:59:59.000' AND ''20180131 04:59:59.000' should both be on the same day, ('20180130'). This doesn't make any sense, as Days don't overlap like that. Thus the latter time would show '20180131', as it's exactly 24 hours later.
If the former time should actually be '20180129', then change -17999 to -18000, or SECOND,-17999 to HOUR, -5.

this will do too:
select cast(dateadd(second, -17999,Transfertime) as date)
being 17999 = 4hs59m59s in seconds

Related

Date difference, two variables in SQL

The problem: I am writing a query to check if the date from a given column is 6 weeks from another column.
I have tried DATEDIFF for other date checks, but that has been with a fixed date as one of the variables. I have two different variables in this case.
My code attempt:
SELECT *
DATEDIFF(d, ifc_forecast, date_complete)
FROM ifc_file
ORDER BY
ifc_forecast DESC
This could be as simple as:
SELECT DATEDIFF(wk, date1, date2) FROM table...
provided that your fields/variables are proper datetime columns.
Reference: DATEDIFF (Transact-SQL)
But probably you'll get a more accurate result by counting the number of days instead, so:
SELECT DATEDIFF(day, date1, date2) FROM table...
6 weeks = 42 days.

Date time query SQL SERVER

I have Date Column Order_Date In date Time format Isdat
14/05/2018 13:13:06 This is format) , I need To Extract Today's Order before 14:00 P:M 'O' Clock and in Second Column I want to extract order after 15:00 P:M i.e Time from 15:00 P:M till 23:00 P:M in SQL SERVER,
Date Is in 24:00 Hor Format.
In output Order_date Should be 'yyyy-MM-dd hh:mm:ss ' Format
Like the others have said, the first thing you need to do is fix your data; storing a date as a varchar is a bad design choice. Always use a data type that is representative of you data; stores dates as a date, numbers as an int/decimal, etc.
According to the [documentation] there is no style code for dd/MM/yyyy hh:mm:ss, however, a quick SQL as below told me that style code 103 does work:
DECLARE #date varchar(50) = '31/05/2017 19:12:56';
WITH N AS (
SELECT 1 AS i
UNION ALL
SELECT i + 1
FROM N
WHERE I + 1 <= 150)
SELECT I, TRY_CONVERT(datetime2(0),#Date,I) AS Conversion
FROM N
OPTION (MAXRECURSION 150);
So, firstly, let's fix that data of yours. So, let's add the new column in and drop your old one.
ALTER TABLE YourTable ADD OrderDate datetime2(0);
UPDATE YourTable
SET OrderDate = CONVERT(datetime2(0),YourDateColumn,103);
GO
ALTER TABLE YourTable DROP COLUMN YourDateColumn;
EXEC sp_rename 'dbo.YourTable.OrderDate','YourDateColumn','COLUMN';
Ok, now we've got rid of your awful datatype, and got your new column. Good.
Now, you want to specifically query time here; if you're doing that, ideally you want to separate the value of the time and date out. Using something like WHERE CONVERT(time, YourDateColumn) BETWEEN '14:00' AND '15:00' makes the query non-SARGHable. Thus let's use a couple of computed columns for that:
ALTER TABLE YourTable ADD OrderDate AS CONVERT(date, YourDateColumn);
ALTER TABLE YourTable ADD OrderTime AS CONVERT(time, YourDateColumn);
Now, to your question at hand: "I need To Extract Today's Order before 14:00 P:M 'O' Clock and in Second Column I want to extract order after 15:00 P:M i.e Time from 15:00 P:M till 23:00 P:M in SQL SERVER". honestly, this is non-sensical; putting different orders based on time in different columns? I have no idea what you mean here, I'm afraid, and I have no sample data or expected results to work with. Thus, instead, i'll show you how to return orders after 14:00 but before '15:00` on a specific date:
SELECT *
FROM YourTable YT
WHERE OrderDate = '20170515'
AND OrderTime >= '14:00'
AND OrderTime < '15:00';
If you need more detail than that, you have a lot of comments asking you for more detail; I suggest you have a look at those. :)

SQL Server : Comparing Time

I am trying to compare time in my SQL query. However, when I run the query, I get zero result but I can see that in the table, there are records that should appear.
The query is as such:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '26/08/2015'
AND StartTime <= CONVERT(varchar(5), GETDATE(), 108)
The StartDate is stored in the database as YYYY-MM-DD and it seems to work fine when I query only with the date.
However, when I add the StartTime is when things don't work. StartTime stores the value in the 24 hour clock format.
What am not doing right?
Thanks
Use a correct datetime format:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '2015-08-26' AND StartTime <= cast(GETDATE() as date)
Don't compare date/time values as strings. The data types are built into the language. Use them.
I have not explicitly used this scenario but comparing dates can be a problem depending on how the fields are compared.
eg: '28/07/2015' is not less than your startdate as 28 > 26.
You could try comparing dates reformatted into a YYYYMMDD format.
Cheers.

Informix SQL Compare DateTime value on Where Statement

I have a datetime field called entrytimestamp, with content of the field is for example: 2014-01-07 16:20:00. I would like to query all the data that has entrytimestamp after 09:00:00 o'clock, regardless what date it was.
I have a prototype query:
select *
from trading
where to_char(entrytimestamp, "%H%M%S") >= "090000"
But I think it is logically a mistake, because it will compare the text string, not the sequence value. What is the right way to do it?
Use the EXTEND() function to extract the time part:
select *
from mytable
where extend(entrytimestamp, hour to second) > '09:00:00'
I dont know if it performs well,
but you could compare directly with the time portion of the datetime,
i think a cast here should perform pretty fast (just cuts off the date)
select *
from (select getdate() as mydatetime) as data
where cast(mydatetime as time) > cast('09:00:00' as time)
EDIT, just noticed this was for Informix SQL, so not sure it works then, Sorry

SQL Server: Get data for only the past year

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])