Date difference, two variables in SQL - 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.

Related

SQL: Trying to select records 7 days before date

I have a table with a date field called oppo_installdate. This is a date in the future, and I basically want to select records where this date is 7 or fewer days from the current date. I have tried to do this with the query below but it is older returning dates from 2019 as well, and I'm not sure why that's happening.
select * from [CRM_Test].[dbo].[Opportunity]
where (GETDATE() >= DATEADD(day,-7, oppo_installdate))
Could anyone suggest a better way of doing this?
Whenever you're using a WHERE always try to apply any functions to constants, or other functions, never your columns. DATEADD(day,-7, oppo_installdate) will make the query non-SARGable, and could slow it down as any indexes won't be able to be used.
It seems like what you simply want is:
SELECT *
FROM [dbo].[Opportunity]
WHERE oppo_installdate >= DATEADD(DAY, 7, GETDATE());
Note that GETDATE returns a datetime, so if you want from midnight 7 days ago, you would use CONVERT(date,GETDATE()) (or CAST(GETDATE() AS date)).
Use below condition-
select * from [CRM_Test].[dbo].[Opportunity]
where oppo_installdate>= DATEADD(day,-7, GETDATE()) and oppo_installdate<=getdate()
This should give you the records where oppo_installdate is 7 or fewer days away from now:
SELECT *
FROM [dbo].[Opportunity]
WHERE oppo_installdate <= DATEADD(DAY, 7, GETDATE())
and oppo_installdate > getdate();

SQL WHERE clause to pick data for last 7 days

I want to build a view on the server with a SELECT statement and pick all records that are created at the last 7 days?
Original creation_date field is in varchar like '18/11/08' and I use the CONVERT(datetime, creation_date,11) to convert it into 2018-11-08 00:00:00.000, but I don't know how to do in the WHERE clause, so it only selects all records created for last 7 days.
use where clause like below
select t.* from your_table t
where CONVERT(datetime, creation_date,11)>= DATEADD(day,-7, GETDATE())
In order to get the best performance, you should keep the calculation away from the column:
SELECT *
FROM <YourTable>
WHERE creation_date >= CONVERT(char(8), DATEADD(day,-7, GETDATE()), 11)
This will handle it well because of the format of the varchar - yy/mm/dd. Would not have worked with all formats
The best thing to do is store dates properly to begin with - in a column with a Date data type.
Assuming you can't change the database structure, you can use DateDiff with GetDate():
SELECT <ColumnsList>
FROM <TableName>
WHERE DATEDIFF(DAY, CONVERT(datetime, creation_date,11), GETDATE()) <= 7
Of course, you need to replace the <ColumnsList> with the list of columns and <TableName> with the actual table name.

How to compare datetime in SQL Server?

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

Subtract two dates in Microsoft SQL Server

I want to subtract 2 dates in MS SQL Server.
Example:
Current date Last used date
'2016-03-30' '2015-02-03'
Current date refers to today's date, "Last used date" is a measure.
How to write a query in SQL Server?
I have this but doesn't work (it says "Operand data type is invalid for subtract operator")
select
CONVERT(DATE, GETDATE()) - CONVERT(DATE, LastUsedDate)
from
databasename
SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate
Output DiffDate 61
More practice please refer below W3 school:
https://www.w3schools.com/sql/func_sqlserver_datediff.asp
Here you don't have to cast GETDATE() to date, as it is already datetime datatype. So your query will be as follows
SELECT DATEDIFF(day,CAST(LastUsedDate as date),GETDATE()) AS DifferneceDays
FROM TableName
The normal function to use is datediff():
select datediff(day, cast('2016-02-03' as date), cast('2016-03-30' as date))
You can subtract datetime values, but not dates. Alas.

query to select data from this day [duplicate]

This question already has answers here:
In SQL Server, what is the best way to filter items for an entire day
(3 answers)
Closed 8 years ago.
I have a database table that has Datelogged columns from type Datetime (Sql server 2008 r2)
The Datelogged value is like this 2014-10-22 12:57:36.583
I want to do a query to select all the rows that its date is today (I care about year, month, and day) but not (hour, second.)
This is my query
string query = "SELECT * FROM Orders WHERE PrintTime is NULL WHERE Datelogged = #Datelogged";
but I didn't know what should I do to tell the query to compare just on year-month-day
Based on #Aaron Bertrand comment
It appears that it is better to use a Date Range from current day midnight (00:00:00) to < tomorrow at midnight.
Query copied from his comment.
DateLogged >= CONVERT(DATE, #DateLogged) AND
DateLogged < DATEADD(DAY, 1, CONVERT(DATE, #DateLogged))
Also see: Bad habits to kick : mis-handling date / range queries By Aaron Bertrand
(Old Answer)
You can use CONVERT(DATE, Datelogged) to get Date part without time.
"SELECT * FROM Orders WHERE PrintTime is NULL AND CONVERT(DATE, Datelogged) = #Datelogged"
Make sure you pass the parameter value using Date property in C# like:
cmd.Paramaters.AddWithValue("#Datelogged", DateTime.Today);// or DateTime.Now.Date
Also make sure to remove multiple WHERE from your query and use AND or OR to combine two conditions depending on your requirement.
Get the minimum date time range for current date and maximum date time range for today. Then, compare it with the logged date value.
Conversion operator on any table column adds extra conversion overhead and leads to inefficient use of index. Should be avoided when possible.
SELECT * FROM Orders
WHERE PrintTime is NULL
AND (Datelogged > dateadd(DD, -1, cast( GETDATE() as date)) AND Datelogged < dateadd(DD, 1, cast( GETDATE() as date)));