Там может быть более простой способ, но следующее дает желаемый результат.Сначала мы создаем объединенный набор записей чатов, которые мы начали, и чатов, которые мы получили, затем мы определяем номер строки для «другой» группы, а затем отфильтровываем только одну строку для каждой группы.
declare @Message table ([From] varchar(1), [To] varchar(1), [DateTime] int, msg varchar(1));
insert into @Message ([From], [To], [DateTime], msg)
select 'A', 'B', 1, 'x'
union all
select 'B', 'A', 2, 'x'
union all
select 'B', 'A', 3, 'x'
union all
select 'A', 'B', 4, 'x'
union all
select 'C', 'A', 8, 'x'
select [From], [To], [DateTime], Msg
from (
select *
-- Calculate a row number per other party by time
, row_number() over (partition by case when [Type] = 0 then [To] else [From] end order by [DateTime] desc) Row#
from (
-- Get chats we initiated
select 0 [Type], [From], [To], [DateTime], Msg
from @Message
where [From] = 'A'
union all
-- Get chats we recevied
select 1 [Type], [From], [To], [DateTime], Msg
from @Message
where [To] = 'A'
) X
) Y
where Row# = 1