if (IsGroupByPhone != null && IsGroupByPhone.isEquality && IsGroupByPhone.Value == true)
{
/*
select
max(Id) as Id
from (select
m.Id as Id,
CASE WHEN m.DirectionMessage = 1 THEN m."From" ELSE m."To" END as Phone
from UC_AsteriskCall ac
join UC_Message m on ( ac.Id = m.Id )
where m.IsDeleted = 0) as ttt group by Phone
*/
string queryDirectionMessage = "";
if(DirectionMessage != null && DirectionMessage.isEquality)
queryDirectionMessage += $" and m.DirectionMessage = {(int)(DirectionMessage.Value)} ";
if (listDirectionMessage != null && listDirectionMessage.isEquality && listDirectionMessage.Value != null && listDirectionMessage.Value.Count > 0)
queryDirectionMessage += $" and m.DirectionMessage in ( {String.Join("," , listDirectionMessage.Value)} ) ";
string query = $"select max(Id) as Id from (select m.Id as Id, CASE WHEN m.DirectionMessage = 1 THEN m.\"From\" ELSE m.\"To\" END as Phone from UC_AsteriskCall ac join UC_Message m on ( ac.Id = m.Id ) where m.IsDeleted = 0 {queryDirectionMessage}) as ttt group by Phone";
query = $" this_1_.Id in ({query}) ";
criteria.Add(Expression.Sql(new SqlString(query)));
}