Actually, I had something slightly different:declare @t table (Entry_Time datetime, Exit_Time datetime)insert @tselect '1900-01-01 21:34:00.000', '1900-01-02 07:00:00.000' union allselect '1900-01-01 23:00:00.000', '1900-01-02 08:10:00.000' union allselect '1900-01-01 21:58:00.000', '1900-01-02 07:00:00.000' union allselect '1900-01-01 18:49:00.000', '1900-01-02 04:06:00.000' union allselect '1900-01-01 20:57:00.000', '1900-01-02 06:13:00.000' union allselect '1900-01-01 18:30:00.000', '1900-01-02 04:00:00.000' union allselect '1900-01-01 21:39:00.000', '1900-01-02 07:00:00.000' union allselect '1900-01-01 17:31:00.000', '1900-01-02 04:48:00.000' union allselect '1900-01-01 23:00:00.000', '1900-01-02 03:00:00.000'select Entry_time ,Exit_time ,[Hours_10-6] = datediff(hour, case when entry_time < '1900-01-01 22:00:00.000' then '1900-01-01 22:00:00.000' else entry_time end, case when exit_time > '1900-01-02 06:00:00.000' then '1900-01-02 06:00:00.000' else exit_time end)from @tOUTPUT:Entry_time Exit_time Hours_10-6----------------------- ----------------------- -----------1900-01-01 21:34:00.000 1900-01-02 07:00:00.000 81900-01-01 23:00:00.000 1900-01-02 08:10:00.000 71900-01-01 21:58:00.000 1900-01-02 07:00:00.000 81900-01-01 18:49:00.000 1900-01-02 04:06:00.000 61900-01-01 20:57:00.000 1900-01-02 06:13:00.000 81900-01-01 18:30:00.000 1900-01-02 04:00:00.000 61900-01-01 21:39:00.000 1900-01-02 07:00:00.000 81900-01-01 17:31:00.000 1900-01-02 04:48:00.000 61900-01-01 23:00:00.000 1900-01-02 03:00:00.000 4
Be One with the OptimizerTG