Get record with two datetimes - sql

I have an issue where I'm trying to get an specific record where I have two dates to get an record.
The date are as follows:
StartTime: '2018-03-02 09:00:00.000'
EndTime : '2018-03-02 11:00:00.000'
The table looks like this:
From the dates above im trying to get the row number 5.
I have tried it like so:
SELECT *
FROM [data].[EmergencyOrders]
WHERE [Workcenter] = #Workcenter
AND [StartDatetime] > #StartTime
AND ISNULL([EndDatetime], GETDATE()) < #StopTime
But can't seem to get it to work correctly.

If you want to know records containing both StartTime and EndTime then you do
WHERE #StartTime BETWEEN [StartDatetime] AND ISNULL([EndDatetime], GETDATE())
AND #EndTime BETWEEN [StartDatetime] AND ISNULL([EndDatetime], GETDATE())
Now the problem I see is if you data range overlap with two ranges. In that case you will have two status. For that I suggest you calculate overlap ranges and select the last one.
Determine Whether Two Date Ranges Overlap
SELECT TOP 1 *
FROM [data].[EmergencyOrders]
WHERE [Workcenter] = #Workcenter
WHERE #StartTime <= ISNULL([EndDatetime], GETDATE())
AND #EndTime >= [StartDatetime]
ORDER BY EmergencyID DESC

I'm guessing you want to get those records which intersect with your date range which means you need something like the below SQL:
SELECT *
FROM [data].[EmergencyOrders]
WHERE
[Workcenter] = #Workcenter AND
(([StartDatetime] BETWEEN #StartTime AND #StopTime) OR
(ISNULL([EndDatetime], GETDATE()) BETWEEN #StartTime AND #StopTime)

Related

SQL : Get yesterdays day with a certain timestamp

i am trying to get yesterdays date in SQL SERVER with a certain timestamp.
I know how to get yesterdays date in SQL without the timestamp using the following query :
Which gives me every startdate starting from '00:00:00':
SELECT se.startdate
FROM sessions se
WHERE se.startdate >= DATEADD(day, -1, CAST(GETDATE() AS date))
Instead I want to get the yesterdays date with a certain timestamp.
For this example every startdate starting from '06:00:00'(AM). Like shown below:
SELECT se.startdate
FROM sessions se
WHERE se.startdate >= '05-09-2022 06:00:00'
If I do it the way it was shown in the second example I would have to change the day manually, which would obviously repetitive.
Is there a way to combine the first example with second one so that we get always yesterdays date at
'06:00:00' ?
(OR ANY GIVEN TIME )
Might as well add another solution, DATETIMEFROMPARTS:
DECLARE #Yesterday date = DATEADD(DAY, -1, GETDATE());
SELECT DATETIMEFROMPARTS(YEAR(#Yesterday),MONTH(#Yesterday),DAY(#Yesterday),6,0,0,0);
For example 06:20:40 of the previous day:
select DATEADD(second, (6 * 60 + 20 ) * 60 + 40, cast(DATEADD(day, -1, cast(GETDATE() AS date)) as datetime)) t
you can do it this way:
SELECT DATEADD(day, DATEDIFF(day, 1, GETDATE()), '06:00:00')

finding missing dates in a time interval (SQL)

I am a bit of a noob with SQL, so I was searching for some bit of code that might help me find missing date values for a time interval when I stumbled upon this code.
DECLARE #StartDate DATETIME DECLARE #EndDate DATETIME
SET #StartDate ='2014-03-01' SET #EndDate = GETDATE()
;WITH Dates(Date) AS
(
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #StartDate)) AS Date
UNION ALL
SELECT DATEADD(day, 1, Date) AS Date
FROM Dates
WHERE Date <= #EndDate
)
SELECT d.Date, r.Value
FROM Dates d
LEFT JOIN Times r ON d.Date = r.Date
Link to the code
It works really well for my problem but I am not able to understand how it increments the date.
I would ask the author but their blog no longer exists and their twitter is inactive too.
Edit: someone said the post is lacking a question. I want to know how this CTE is recursively adding the +1 to each date from #StartDate to #EndDate.
This is a recursive CTE, or Common Table Expression.
The first line of of the CTE SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #StartDate)) AS Date is the seed, or root portion. The next UNION section takes that date, adds a day, and recurses.
Notice that inside the Dates block you are selecting FROM Dates, so it will continue produce rows with an incremented date until the WHERE clause is satisfied.

Anything that expected within the last 10 days back should be received if not ignore them in SQL

I need to ignore data anything that expected within the last 10 days back should be received if not ignore it. I am not sure how to write this in SQL. I have EXPDATE column. I am not sure my statement correct or not.
I believe the logic should be like this
Expected Date + 10 Days < Today`s date?
GETDATE() < DATEADD(DAY, +10, GETDATE()) - I found this online but where can I plug in my ExpectedDate column?
Thanks in advance!!
You can do it either way-
First add 10 days to EXPDATE and compare it with todays date like below.
select * from MyTable Where DATEADD(DAY, 10, EXPDATE) < GETDATE()
The other way, you can substract 10 days from today and compare it with EXPDATE.
select * from MyTable Where DATEADD(DAY, -10, GETDATE()) > EXPDATE
I would prefer 2nd one and would use variable to calculate 10 days back date as it's constant and then use it in where clause like below.
Declare #myDate datetime
SET #myDate = DATEADD(DAY, -10, GETDATE())
select * from MyTable Where #myDate > EXPDATE

SQL Greater than, Equal to AND Less Than

I want to create a query like the following, But im unsure of how to code it correctly,
I want it to return all bookings within 1 hour of a StartTime, Here is what i came up with:
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime <=> 1.00
Is the possible? or Is there a way round it?
Everything ive found on the web hasn't been about using Greater than, Equal to and Less Than all in the same query.
Supposing you use sql server:
WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
AND DATEADD(HOUR, 1, GetDate())
If start time is a datetime type then you can use something like
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000'
AND StartTime <= '2012-03-08 01:00:00.000'
Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.
You can use the GETDATE() function to get todays current date.
declare #starttime datetime = '2012-03-07 22:58:00'
SELECT BookingId, StartTime
FROM Booking
WHERE ABS( DATEDIFF( minute, StartTime, #starttime ) ) <= 60
Somthing like this should workL
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

SQL statement to select all rows from previous day

I am looking for a good SQL Statement to select all rows from the previous day from one table. The table holds one datetime column. I am using SQL Server 2005.
get today no time:
SELECT dateadd(day,datediff(day,0,GETDATE()),0)
get yestersday no time:
SELECT dateadd(day,datediff(day,1,GETDATE()),0)
query for all of rows from only yesterday:
select
*
from yourTable
WHERE YourDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND YourDate < dateadd(day,datediff(day,0,GETDATE()),0)
To get the "today" value in SQL:
convert(date, GETDATE())
To get "yesterday":
DATEADD(day, -1, convert(date, GETDATE()))
To get "today minus X days": change the -1 into -X.
So for all yesterday's rows, you get:
select * from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
It's seems the obvious answer was missing. To get all data from a table (Ttable) where the column (DatetimeColumn) is a datetime with a timestamp the following query can be used:
SELECT * FROM Ttable
WHERE DATEDIFF(day,Ttable.DatetimeColumn ,GETDATE()) = 1 -- yesterday
This can easily be changed to today, last month, last year, etc.
SELECT * from table_name where date_field = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY);
Its a really old thread, but here is my take on it.
Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.
SELECT * FROM TABLE_NAME WHERE
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0
In the above case X will be -1 for yesterday's records
This should do it:
WHERE `date` = CURDATE() - INTERVAL 1 DAY
Can't test it right now, but:
select * from tablename where date >= dateadd(day, datediff(day, 1, getdate()), 0) and date < dateadd(day, datediff(day, 0, getdate()), 0)
In SQL Server do like this:
where cast(columnName as date) = cast(getdate() -1 as date)
You should cast both sides of the expression to date to avoid issues with time formatting.
If you need to control interval in more detail, then you should try something like:
declare #start datetime = cast(getdate() - 1 as date)
declare #end datetime = cast(getdate() - 1 as date)
set #end = dateadd(second, 86399, #end)
Another way to tell it "Yesterday"...
Select * from TABLE
where Day(DateField) = (Day(GetDate())-1)
and Month(DateField) = (Month(GetDate()))
and Year(DateField) = (Year(getdate()))
This conceivably won't work well on January 1, as well as the first day of every month. But on the fly it's effective.
Well, its easier to cast the datetime column to date and than compare.
SELECT * FROM TABLE_NAME WHERE cast(COLUMN_NAME as date) =
dateadd(day,0, convert(date, getdate(), 105))
A simple alternative
Select GETDATE() - 1
Change 1 to go back that many number of days
PS : This gives you timestamp accuracy.
This worked a charm:
SELECT * FROM mytable WHERE date(mydate) = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
subdate(now(),1) will return yesterdays timestamp
The below code will select all rows with yesterday's timestamp
Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)