SELECT * FROM (
  SELECT
    U1.UserID,
    U1.FullName,
    U1.Office365Email,
    IF(U1.Status = 1, "Active", "Cancelled") AS UserStatus,
    U1.EmployeeCode,
    BR.BranchName,
    U1.JobTitle,
    U1.IsResource
  FROM
    taUsers AS U1
      LEFT JOIN (SELECT UserID, BranchID, FromDate FROM taUserBranchMember) AS BM ON (BM.UserID = U1.UserID)
      LEFT JOIN taBranches AS BR ON (BR.BranchID = BM.BranchID)
  WHERE
    ((BM.FromDate IS NULL) OR (BM.FromDate = (SELECT MAX(N.FromDate) FROM taUserBranchMember AS N WHERE (N.UserID = U1.UserID) AND (N.FromDate <= NOW()))))
) AS X
WHERE
  1
  @pFilter
