• Try:

    with CTE_In as

    (

    select

    Employee,

    [Function],

    [DateTime],

    ROW_NUMBER() OVER(PARTITION BY Employee, [Function] ORDER BY [DateTime]) as RN

    from MyTable

    where

    [Function] in (1, 3)

    )

    select

    i.Employee,

    i.[Function] / 2 + 1 as [Type],

    i.[DateTime] as DateTimeIn,

    (select top 1 o.[DateTime]

    from MyTable as o

    where

    o.Employee = i.Employee and

    o.[Function] = i.[Function] + 1 and

    o.[DateTime] > i.[DateTime] and

    (o.[DateTime] < ni.[DateTime] or ni.[DateTime] is null)

    order by

    o.[DateTime]) as DateTimeOut

    from CTE_In as i

    left join CTE_In as ni

    on ni.Employee = i.Employee and

    ni.[Function] = i.[Function] and

    ni.RN = i.RN + 1

    Hope this helps.