0
我有一個時間框架:分類間隔日夜SQL服務器
FROMTIME:06:01:00 - TOTIME:23:59:00 = DAY
FROMTIME:23:59:01 - TOTIME:06:00:00 = Night
我有一輛車TIME_IN和TIME_OUT。 如何分類汽車間隔時間是DAY或Night或DayAndNight 。我使用的代碼,但它的執行很長一段時間:
Declare @From_Time_Day time
\t \t ,@To_Time_Day time
\t \t ,@From_Time_Night time
\t \t ,@To_Time_Night time
\t \t ,@Midnight time
\t \t
set @From_Time_Day = (select FROM_TIME from DAY_STATUS where DAY_CHECK=1)
set @To_Time_Day = (select TO_TIME from DAY_STATUS where DAY_CHECK=1)
set @From_Time_Night = (select FROM_TIME from DAY_STATUS where DAY_CHECK=2)
set @To_Time_Night = (select TO_TIME from DAY_STATUS where DAY_CHECK=2)
set @Midnight = '00:00:00'
select * from (
select
\t (case when (
\t \t \t \t cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as date)
\t \t \t \t = cast(Data.IO_TIME as date)
\t \t \t \t)
\t \t then
\t \t \t \t (
\t \t \t \t case when (
\t \t \t \t \t \t cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as time) >= @From_Time_Day
\t \t \t \t \t \t and cast(Data.IO_TIME as time) <[email protected]_Time_Day
\t \t \t \t ) then 'DAY'
\t \t \t \t when (
\t \t \t \t cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as time) >= @From_Time_Night
\t \t \t \t and cast(Data.IO_TIME as time) < @Midnight
\t \t \t \t \t \t ) then 'Night'
\t \t \t \t \t when (
\t \t \t \t \t cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as time) >= @Midnight
\t \t \t \t \t \t and cast(Data.IO_TIME as time) <= @To_Time_Night
\t \t \t \t \t ) then 'Night'
\t \t \t \t \t else 'DayAndNight' end
\t \t \t \t)
\t \t when (
\t \t \t \t cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as date)
\t \t \t \t <> cast(Data.IO_TIME as date)
\t \t \t \t)
\t \t then \t (
\t \t \t \t case when(
\t \t \t \t \t \t (cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as time) >= @From_Time_Night and
\t \t \t \t \t \t cast((select top 1 IO_TIME from IO_INFO where IO_STATUS= 'IN' and CA_ID = Data.CA_ID and IO_ID < Data.IO_ID order by IO_ID desc) as time) < @Midnight)
\t \t \t \t \t \t and (cast(Data.IO_TIME as time)>[email protected] and cast(Data.IO_TIME as time)<[email protected]_Time_Night)
\t \t \t \t ) then 'Night'
\t \t \t \t else 'DayAndNight' end
\t \t )
\t \t end
) as INTERVAL
from IO_INFO as Data where IO_STATUS = 'OUT'