create table #tmp
(
shiftstarttime datetime,
shiftendtime datetime
)
insert into #tmp values ('1-Jan-2017 7:00:00','1-Jan-2017 15:30:00')
insert into #tmp values ('1-Jan-2017 15:30:00','1-Jan-2017 23:59:59')
insert into #tmp values ('2-Jan-2017 00:00:00','2-Jan-2017 06:59:59')
declare @currdate datetime=getdate()
declare @lastdate datetime=dateadd(d,-1,getdate())
declare @tab table
(
RankID int identity,
starttime datetime,
endtime datetime
)
insert into @tab
select dateadd(d,datediff(d,shiftstarttime,@currdate),shiftstarttime), dateadd(d,datediff(d,shiftendtime,@currdate),shiftendtime)
from #tmp
UNION
select dateadd(d,datediff(d,shiftstarttime,@lastdate),shiftstarttime), dateadd(d,datediff(d,shiftendtime,@lastdate),shiftendtime)
from #tmp
select starttime as LastThirdShiftStartTime,endtime as LastThirdShiftEndTime
from @tab where RankID = (select RankID from @tab where @currdate between starttime and endtime)-3
select starttime as LastRunningShiftStartTime,endtime as LastRunningShiftEndTime
from @tab where RankID = (select RankID from @tab where @currdate between starttime and endtime)-1
drop table #tmp
你可以試試這個示例代碼。我已將換檔時間存儲在臨時表中,並根據當前服務器時間,它將爲您提供最後的第3次換檔開始和結束時間以及上次換檔開始和結束時間。
不明確的問題。 「Last Three Shift Start Time」是什麼意思?你的意思是最後一秒?那樣的話「Last Three Shift End Time」必須是2017-03-13 15:30:00 PM吧? –
更新了問題&是我需要上次第三次班次開始時間和最後三班班次結束時間。例如:如果我在第一班(14-Mar-2017 7:00:00 AM)的意思。我需要輸出最後一次襯衫開始時間(14-Mar-2017 12:00:00 AM)和結束時間(2017年3月14日6:59:59上午)&最後三分鐘開始時間(2017年3月14日:00:00 AM)結束時間(14-Mar-2017 06:59:59 AM) – Dhamo
仍然困惑! 「Last Third Shift End Time」和「Last Running Shift End Time」將如何相同-2017-03-14 06:59:59.000? –