Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
mukejee
Starting Member
5 Posts |
Posted - 2014-02-17 : 06:10:27
|
Hi Experts,I need to write a SQL for the below scenario. Please help me.ID shiftname shiftstart shiftend1 ABC 9:00AM 4:00PM2 BCD 4:00PM 10:00PMNow I have another tableID Empname Intime OutTime Shiftname1 Ram 10:00AM 3PM ABC2 Sam 11:00AM 4PM ABCSo here i need to check the intime and outtime against the time shift start and shiftend in the 1st table and populate the shift name. How can I achieve it?ThanksMUkesh |
|
stepson
Aged Yak Warrior
545 Posts |
Posted - 2014-02-17 : 06:52:48
|
[code];with _shiftNameAS (select 1 [ID], 'ABC' [shiftName], CAST('9:00AM' as TIME) [shiftStart],CAST('4:00PM' as TIME) [shiftEnd] union all select 2 ,'BCD',CAST('4:00PM' as TIME),CAST('10:00PM' as TIME)),shiftDailyAS( select 1 [ID],'Ram'[EmpName],CAST('10:00Am' as TIME) [InTime],CAST('3:00PM'as TIME) [OutTime] union all select 2 ,'Sam', CAST('11:00AM' as TIME), CAST('4:00PM' as TIME))[/code][code]SELECT * FROM shiftDaily SD OUTER APPLY ( SELECT TOP 1 [shiftName] FROM _shiftName SN WHERE SD.InTime>=SN.[shiftStart] AND SD.OutTime<=SN.[shiftEnd] ORDER BY ID asc )SN [/code]depinding of what type are column , where is another :[code]SELECT * FROM shiftDaily SD OUTER APPLY ( SELECT TOP 1 [shiftName] FROM _shiftName SN WHERE CAST(SD.InTime as TIME)>=CAST(SN.[shiftStart] as TIME) AND CAST(SD.OutTime as TIME) <=CAST(SN.[shiftEnd] as TIME) ORDER BY ID asc )SN [/code]SsabinWeb MCP |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2014-02-17 : 07:11:45
|
[code]SELECT t1.*,t2.shiftnameFROM Table2 t2CROSS APPLY (SELECT TOP 1 shiftnameFROM table1ORDER BY DATEDIFF(ss,shiftstart,Intime),DATEDIFF(ss,shiftend,Outtime))t1[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|