SQL query for in between data in a table - sql-server

Please give me right answer for this question
This is the table time_names and its structure:
time_id time_name
------- ----------
1 5:00 AM
2 5:15 AM
3 5:30 AM
4 5:45 AM
5 6:00 AM
6 6:15 AM
... .....
... .....
70 10:15 PM
71 10:30 PM
72 10:45 PM
73 11:00 PM
74 11:15 PM
75 11:30 PM
76 11:45 PM
time_id is INT, time_name is varchar datatype.
Here I want show only 8:30 AM to 11:00 PM between all data
Please give me any query

Since you're on SQL Server 2008, you can simply cast the time_name to a TIME datatype:
SELECT time_id, time_name
FROM dbo.time_names
WHERE CAST(time_name AS TIME) BETWEEN '08:30 AM' AND '11:00 PM'
But seriously: if you store a time value - WHY aren't you using the appropriate TIME datatype for it??

select time_name between will not work, because it's string comparison. You have to use time_id or convert time, for example like this
select *
from time_names
where convert(nvarchar(8), convert(datetime, time_name, 109), 108) between '08:30' and '23:00'
Here I'm converting time from string to real date time and then converting it into 24 hours format, so you can use string compare.
you also can use time type
select *
from time_names
where convert(time, time_name, 109) between '08:30' and '23:00'
http://msdn.microsoft.com/en-us/library/ms187928.aspx
I also have to say that this table design looks really bad. You have to store date and time in the columns with apropriate types.

I´m not a SQL user but try to convert the 'time_name' to DateTime data type and use a select between DateTime1 AND DateTime2

You can use the following query
CREATE table #Time(
time_id int PRIMARY key,
time_name varchar(255))
INSERT INTO #Time values(1, '5:00 AM')
INSERT INTO #Time values(2, '5:15 AM')
INSERT INTO #Time values(3, '5:30 AM')
INSERT INTO #Time values(4, '5:45 AM')
INSERT INTO #Time values(5, '6:00 AM')
INSERT INTO #Time values(6, '6:15 AM')
INSERT INTO #Time values(7, '6:30 AM')
INSERT INTO #Time values(8, '6:45 AM')
select * from #Time
where CAST(time_name as datetime) between CAST('5:30 AM' as datetime) and CAST('6:00 AM' as datetime)
DROP TABLE #Time

Related

Oracle: how to convert varchar2 to time?

How can I convert varchar2 (i.e. string) to timestamp?
The original data
08:00 AM - 06:00 PM
10:00 AM - 04:00 PM
so I can compare between them.
--STORE
CREATE TABLE STORE(
StoreID VARCHAR2(10) NOT NULL,
StoreAddress VARCHAR2(50),
WeekDaysHours VARCHAR2(20),
WeekendHours VARCHAR2(20),
PRIMARY KEY(StoreID));
The values
INSERT INTO STORE VALUES ('S004', 'High Drive', '09:00 AM - 05:00 PM', '08:00 AM - 06:00 PM' );
INSERT INTO STORE VALUES ('S005', 'Snake Rd', '09:00 AM - 09:00 PM', '10:00 AM - 04:00 PM' );
If all values follow the same format and are valid (i.e. you don't have something like 08:BX FZ - #7-25 AM), then use substr (to extract each part of the string) and apply to_date function with appropriate format mask. Date portion will be "today"
[EDIT: no, it won't be "today". Quoting #mathguy's comment (thank you, #mathguy)]
Date portion will not be today. The defaults are "current year" and "current month", but the default "day of the month" is 1. The date portion will be the first day of the current month.
I'm modifying my session just to know what is what:
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi';
Session altered.
SQL> with test (col) as
2 (select '08:00 AM - 06:00 PM' from dual)
3 select to_date(substr(col, 1, 8), 'hh:mi am') first_part,
4 to_date(substr(col, 13, 8), 'hh:mi pm') second_part
5 from test;
FIRST_PART SECOND_PART
---------------- ----------------
01.05.2021 08:00 01.05.2021 18:00
SQL>
Now that these are dates, you can compare them.

SQL query to join tables - where one table's datetime does not match the other ones

Joined just to ask this because it is killing me :) Great forum with a lot of great minds!
I simply need to join these two tables, i can only join them on date and time no other columns are available.
Table 1 has for example following columns
Film -----------------Datetime……………………………Duration(minutes)
TITANIC------------2016-01-01 01:00:00-----------------60
Armageddon---------2016-01-01 02:00:00-----------------60
Table 2 has following columns
Date----------------Time
2016-01-01……….01:00:00
2016-01-01……….01:01:00
2016-01-01……….01:02:00
2016-01-01……….01:03:00
…and so on
Table 2 contains info for every minute but table one only one specific time and date per event. so i need to match for every minute in table two with what i got from table one.
Any ideas? i'll take anything that works :) btw sorry for the formatting!
Edit:
Desired result would be something like
TITANIC------------2016-01-01 01:00:00-----------------60
TITANIC------------2016-01-01 01:01:00-----------------60
TITANIC------------2016-01-01 01:02:00-----------------60
Armageddon---------2016-01-01 02:00:00-----------------60
Armageddon---------2016-01-01 02:01:00-----------------60
Armageddon---------2016-01-01 02:02:00-----------------60
And so on...
convert the table 2 date and time to a datetime and see if it is between table 1 datetime and datetime + duration.
SELECT *
FROM table1 t1
JOIN table2 t2 ON CAST(t2.Date AS DATETIME)
+ CAST(t2.Time AS DATETIME) >= t1.Datetime
AND CAST(t2.Date AS DATETIME)
+ CAST(t2.Time AS DATETIME) < DATEADD(MIN,
t1.Duration,
t1.Datetime)
I'm going to make some assumptions as you haven't outlined the table structure.
Your film table is of the following structure:
CREATE TABLE Films ([Film] NVARCHAR(128), [DateTime] DATETIME, Duration INT)
GO
Your Date/Time values table is of the following structure:
CREATE TABLE DateTimeValues ([Date] DATE, [Time] TIME)
GO
Lets insert your values:
--Insert Values for Films
INSERT INTO Films
VALUES ('TITANIC', '2016-01-01T01:00:00', 60),
('Armageddon', '2016-01-01 02:00:00', 60)
GO
--Insert Values for every minute of 2016-01-01
DECLARE #DATETIMEBEGIN DATETIME
SET #DATETIMEBEGIN = '2016-01-01'
DECLARE #DATETIMEEND DATETIME
SELECT #DATETIMEEND = '2016-01-02'
;WITH CTE AS (SELECT DATEADD(day, 0, DATEDIFF(day, 0, #DATETIMEBEGIN)) DateTimeValues
UNION ALL
SELECT DATEADD(MINUTE, 1, DateTimeValues) AS DateTimeValues
FROM CTE
WHERE DateTimeValues < #DATETIMEEND
)
INSERT INTO DateTimeValues
SELECT CONVERT(DATE, DateTimeValues) "Date",
CONVERT(TIME, DateTimeValues) "Time"
FROM CTE
OPTION (MAXRECURSION 0)
GO
Lets make it simple and lets caluclate the start time/end time for each film according to the duration. The query you will need for your desired output is:
;WITH CTEFilms AS
(
SELECT Film,
CONVERT(DATE, [DateTime]) "Date",
CONVERT(TIME, [DateTime]) "StartTime",
CONVERT(TIME, DATEADD(MINUTE,Duration,[DateTime])) "EndTime",
Duration
FROM Films
)
SELECT f.Film,
CAST(dtv."Date" AS DATETIME) + dtv."Time" "DateTime",
Duration
FROM CTEFilms f
INNER JOIN DateTimeValues dtv
ON f.[Date] = dtv.[Date]
AND dtv.[Time] >= f.StartTime
AND dtv.[Time] < f.EndTime
ORDER BY Film, Time
Your Results:
Film DateTime Duration
Armageddon 2016-01-01 02:00:00.000 60
Armageddon 2016-01-01 02:01:00.000 60
Armageddon 2016-01-01 02:02:00.000 60
Armageddon 2016-01-01 02:03:00.000 60
Armageddon 2016-01-01 02:04:00.000 60
...
Armageddon 2016-01-01 02:55:00.000 60
Armageddon 2016-01-01 02:56:00.000 60
Armageddon 2016-01-01 02:57:00.000 60
Armageddon 2016-01-01 02:58:00.000 60
Armageddon 2016-01-01 02:59:00.000 60
TITANIC 2016-01-01 01:00:00.000 60
TITANIC 2016-01-01 01:01:00.000 60
TITANIC 2016-01-01 01:02:00.000 60
TITANIC 2016-01-01 01:03:00.000 60
TITANIC 2016-01-01 01:04:00.000 60
...
TITANIC 2016-01-01 01:55:00.000 60
TITANIC 2016-01-01 01:56:00.000 60
TITANIC 2016-01-01 01:57:00.000 60
TITANIC 2016-01-01 01:58:00.000 60
TITANIC 2016-01-01 01:59:00.000 60
#Eddie B, you did not give out your table structure, i.e. column data types, so I just come up with the following assumed code/data
use tempdb
drop table dbo.t1, dbo.t2;
create table dbo.T1 (film varchar(10), dt datetime, duration int)
create table dbo.T2 (dt varchar(10), tm varchar(10));
go
-- populate the tables with SOME sample data
insert into dbo.T1(film, dt, duration)
values ('Titanic', '2016-01-01 01:00:00', 5), ('Amageddon', '2016-01-01 02:00:00', 4)
insert into dbo.T2 (dt, tm)
values
('2016-01-01', '01:00:00')
, ('2016-01-01', '01:01:00')
, ('2016-01-01', '01:02:00')
, ('2016-01-01', '01:03:00')
, ('2016-01-01', '01:04:00')
, ('2016-01-01', '01:05:00')
, ('2016-01-01', '02:00:00')
, ('2016-01-01', '02:01:00')
, ('2016-01-01', '02:02:00')
, ('2016-01-01', '02:03:00')
, ('2016-01-01', '02:04:00')
, ('2016-01-01', '02:05:00')
, ('2016-01-01', '03:00:00');
go
-- here is the result
select t1.film, [DateTime]= convert(datetime, t2.dt + ' ' + t2.tm), t1.duration
from dbo.t1
inner join dbo.t2
on convert(datetime, t2.dt + ' ' + t2.tm) >= t1.dt
and convert(datetime, t2.dt + ' ' + t2.tm) <= dateadd(minute, t1.duration, t1.dt)
go
Here is the result:

ORA-01847: day of month must be between 1 and last day of month in toad

While insert data inside table having columns as
CREATED 16 Y DATE None 1137152
LASTAROMAUPDATE 44 Y DATE None 0
ORDERDATETIME 58 Y DATE Height Balanced 3095808
and inserting like as show below :to_date('10/11/2014 16:00:50','mm/dd/yyyy hh24:mi:Ss'),
and tried with getdate(),sysdate,to_char etc. Please help me out .
data insert in above columns as :
1)1/23/2013 11:40:08 AM
2)1/23/2013 11:40:08 AM
3)9/19/2010
Help me
1)to_date('1/23/2013 11:40:08 AM', 'MM/DD/YYYY HH:MI:SS AM')
2)to_date('1/23/2013 11:40:08 AM', 'MM/DD/YYYY HH:MI:SS AM')
3)to_date('9/19/2010', 'MM/DD/YYYY')

How to find the nearest time in SQL Server query?

id Bus arrival time
1 6:30
2 7:00
3 9:00
4 10:00
5 15:00
6 16:00
If one bus comes at 6:40 then nearest time should be 6:30
If bus comes at 9:35 nearest time should be 10:00 like wise I need the solution as a T-SQL query
Thanks In Advance,
Anil
declare #checkTime time = '6:40'
select top 1 * from schedule
order by ABS(DATEDIFF(Second, #checkTime, busArrivalTime))
SQLFIDDLE
you can do something like :
DECLARE #TIME TIME = '6:45'
DECLARE #TEMP TABLE(ID int,start time);
insert into #temp values(1, '6:30')
insert into #temp values(1, '7:00')
insert into #temp values(1, '9:00')
insert into #temp values(1, '10:00')
insert into #temp values(1, '15:00')
insert into #temp values(1, '6:30')
insert into #temp values(1, '16:00')
SELECT top(1)start ,ABS(DATEDIFF(MINUTE , #TIME ,START )) as diff
FROM #TEMP
order by diff

DATEDIFF with cutoff time

I'm working on a Room Scheduling application. We have this Room Check Out Rule that we need follow. All
room check out should be 12:00 PM. If the check out date is after 12.00 PM it will be considered additional 1 day.
Below is my T-SQL code that returns 5 days.
SELECT DATEDIFF(day, '3/12/2013 12:00:00 PM', '3/17/2013 3:00:00 PM');
If you see the code above the end date is 3:00:00 PM. How can I tweak this code to return 6 days instead of 5?
What if I have this code?
SELECT CEILING(DATEDIFF(SECOND, '3/12/2013 02:00:00 PM' , '3/17/2013 12:50:36 PM') / (24.0 * 60 * 60))
The above code still returns 5 days instead of 6.
SELECT CEILING(DATEDIFF(SECOND, '3/12/2013 12:00:00 PM', '3/17/2013 12:00:01 PM') / (24.0 * 60 * 60))
The correct way is to subtract 12 hours from StartDate and EndDate, then take a day-diff + 1:
declare #dateStart as datetime, #dateEnd as datetime
set #dateStart = cast('20130301 11:59:59 AM' as datetime)
set #dateEnd = cast('20130301 12:01:01 PM' as datetime)
select
#dateStart,
#dateEnd
select days = 1 + datediff(d,#dateStart,#dateEnd)
select
days = 1 + datediff(d, dateadd(hh, -12, #dateStart), dateadd(hh, -12, #dateEnd))
returns this:
----------------------- -----------------------
2013-03-01 11:59:59.000 2013-03-01 12:01:01.000
days
-----------
1
days
-----------
2
Clearly the second formula is correct, not the first.
Perhaps you can count hours:
SELECT DATEDIFF(hour, '3/12/2013 12:00:00 PM', '3/17/2013 3:00:00 PM');
Therefore, 123 > 120 (or divided by 24 - 5.125 > 5) accounts for 6 days.

Resources