0

I have a table like this

ID          Day  Start End
----------- ---- ----- -----
1           M    7:30  9:30
2           T    7:30  11:30
3           T    12:30 14:30

And another table like this

Day  Start End
---- ----- -----
M    8:30  11:30
T    8:30  10:30

I want to select all records from the first table that is based from the second table.

Example Result :

ID          Day  Start End  
----------- ---- ----- -----
1           M    7:30  9:30 
2           T    7:30  11:30

The result is like that because the first 2 records in the 1st table matched the criterion from the second table. The 1st and 2nd row has the same day and the time clashed with the other one.

5
  • What're the data types of Start and End? Commented Nov 2, 2015 at 4:47
  • And sql-server version is? Commented Nov 2, 2015 at 4:49
  • Do not quote the SQL schema. Use code formatting. Commented Nov 2, 2015 at 4:51
  • @delbertwah are you only getting the first record of the day? because on your table 1 Tuesday you have two records and only get the first one in your output. Commented Nov 2, 2015 at 5:07
  • use where exists.Ok sorry,Guess i didn't read the last para.Can you through few more sample data where time don't clash and output will be different. Commented Nov 2, 2015 at 7:22

1 Answer 1

1

This join will work:

select * 
from t1
join t2 on t1.day = t2.day and t1.end >= t2.start and t1.start <= t2.end

If time columns are varchars you need to cast to time:

select * 
from t1
join t2 on t1.day = t2.day and 
           cast(t1.end as time) >= cast(t2.start as time) and 
           cast(t1.start as time) <= cast(t2.end as time)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.