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()
Related
I have a case compare date, hour of datetime column and current date,hour
select * from tbl where LEFT(EVENT_TIME_column,13) !=LEFT(GETDATE(),13)
EVENT_TIME_column format is '2019-08-15 12:32:40.0000000'
when i perform LEFT(GETDATE(),13) result is 'Aug 15 2019'
can you suggest how to get GETDate() in '2019-08-15 12' (date and hour)
If you want the format yyyy-MM-dd hh then can do this:
SELECT CONVERT(varchar(13),GETDATE(),120);
db<>fiddle
You can find a full list of all the style codes for CONVERT in the documentation: Date and Time Styles
However, it looks like you want to check if the date is within the current hour. That would be:
WHERE EVENT_TIME_column >= DATEADD(HOUR, DATEDIFF(HOUR, 0,GETDATE()),0)
AND EVENT_TIME_column < DATEADD(HOUR, DATEDIFF(HOUR, 0,GETDATE())+1, 0)
This explicitly avoids any functions on the column EVENT_TIME_column; which would make the query non-SARGable.
Don't use string functions on date/time values! There are perfectly good built-in functions:
where convert(date, event_time_column) = convert(date, getdate()) and
datepart(hour, event_time_column) = datepart(hour, getdate())
If you don't care about index usage, then use datediff():
where datediff(hour, event_time_column, getdate()) = 0
You can check this with 2 separate comparison as below. This is for checking Date and Hour part is same as date and hour part if GETDATE() or not.
WHERE CAST(EVENT_TIME_column AS DATE) = CAST(GETDATE() AS DATE)
AND DATEPART(HH,EVENT_TIME_column) = DATEPART(HH,GETDATE())
To check NOT EQUAL TO, Just replace = sign with != sign.
In addition, If I guess correct you are only trying to avoid records from running hour of to date. If this is the case, you can also filter your data with below logic-
WHERE EVENT_TIME_column < DATEADD(hh, DATEDIFF(hh, 0, getdate()), 0)
I am trying to use my query as the current day for my SQL query.
What I am trying below returns 0 records:
select *
from [TEST].[dbo].LIMIT
where endOfDay = GETDATE()
select *
from [TEST].[dbo].LIMIT
where endOfDay = dateadd(dd, datediff(dd, 0, getdate()), 0)
where endOfDay >= getdate() and endOfDay < getdate() + 1
An example date would be 2019-07-09 00:00:00.0
Also if there is no given date for today's date can I get a range of dates?
Any help would be appreciated, thanks.
First, you need to omit the quotes or else 'GETDATE()' is just a string.
Second, to match by "day", you need to strip the time part from the result of GETDATE(), which you can do by using CAST(GETDATE() as DATE) instead:
select *
from [TEST].[dbo].LIMIT
where endOfDay = CAST(GETDATE() as DATE)
For this to work best, the endOfDay column also needs to be of type DATE. If it is something else, you need to also CAST or CONVERT endOfDay to a DATE.
Using quotes makes it looking for a meaningless literal 'GETDATE()' to find nothing
You can use
with LIMIT(today, EndOfDay) as
(
select CONVERT(DATETIME, CONVERT(date, GETDATE())), GETDATE()
)
select EndOfDay
from LIMIT
where EndOfDay >= today and EndOfDay < today + 1;
Demo
Try this:
select *
from [TEST].[dbo].LIMIT
where cast(endOfDay as date) = cast(GETDATE() as date)
SQL Fiddle to see what the date will be compared with.
GETDATE() returns the server's current date and time. Unless you have any records that match that exactly, it doesn't make sense to use GETDATE. It doesn't look like you do based on the endOfDay column name.
The other criteria you show,
dateadd(dd,datediff(dd,0,getdate()),0) is essentially stripping the time off and returning midnight of the current date.
select getdate() 2019-07-11 15:10:09.287
select dateadd(dd,datediff(dd,0,getdate()),0) 2019-07-11 00:00:00.000
Assuming you don't care about time, convert both EndofDay and Getdate to a simple date for comparison.
select * from [TEST].[dbo].LIMIT where convert(date,EndOfDay) = convert(date,getdate())
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)
I have three Shifts in my office.How i can get name of current running shift using Sql Query ?
Table Description is as given below
Id, Name, startTime, hours
1, Shift1, 7:00 am, 8
2, Shift2, 3:00 pm, 8
3, Shift3, 11:00 pm, 8
Thanks in Advance
This is quite a top-level question, so I'm going to give you a top-level answer, rather than writing the code for you, because that way you'll have the tools to solve other problems in future.
I would approach this in 3 stages:
Write a query that selects the end time of each shift based on the startTime and hours columns, i.e. "what time is X hours after time Y". The exact function to use depends which DBMS you use (MySQL, PostgreSQL, MS SQL Server, SQLite, etc), but is likely to be called something like date_add.
Find out how to get the current time in your DBMS (e.g. now(), getdate(), CURRENT_TIME)
Write a WHERE clause that returns rows where a time is between two other times. (Hint: BETWEEN is a keyword in SQL.) Start simple with something you know will always be true, like "2:00 is between 1:00 and 3:00".
Put these together, and you can build the query you wanted: select rows where the current time is between the startTime and the calculated end time.
For SQL Server I think:
select Id, Name, startTime, hours
from table
where
convert(time, getdate()) >= startTime
and convert(time, getdate()) < DATEADD(HH, hours, startTime)
if startTime column type is time.
EDIT
I strongly suggest to change the column to Time
If this cannot happen consider the solution below:
select convert( time, '6:00 am' )
-- result 06:00:00.0000000
select convert( time, '6:00 pm' )
-- result 18:00:00.0000000
So:
create view MyTableView as
select
Id,
Name,
StartTime = convert( time, startTime ),
EndTime = DATEADD(HH, hours, convert( time, startTime ) ),
ShiftDuration = hours
from
MyTable
UPDATE for 24h shift span
select
Id,
Name,
StartTime,
EndTime,
ShiftDuration
from
MyTableView
where
(
( StartTime < EndTime )
and ( convert(time, getdate()) >= StartTime )
and ( convert(time, getdate()) < EndTime )
)
or
(
( StartTime >= EndTime )
and ( convert(time, getdate()) >= StartTime )
and ( convert(time, getdate()) > EndTime )
)
You didn't specify your DBMS, so this is ANSI SQL:
select *
from (
select id, name, start_time, start_time + interval '1' hour * hours as end_Time
from shifts
) t
where current_time between start_time and end_time;
SQLFiddle example: http://sqlfiddle.com/#!15/f5428/1
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)