SELECT
  AP.ClientID,
  AP.AppointmentID,
  AP.ProductID,
  AP.AttendanceDate,
  AP.ConsultantID,
  U1.FullName AS Consultant,
  U2.FullName AS BookedBy,
  CS.FinNumber,
  CS.GroupName AS ClientName,
  CB.BranchName AS ClientBranchName,
  BR.BranchRegion AS BranchRegion,
  B3.BranchRegion AS OnBehalfOfBranch,
  AT.ProductCategory AS ProductCategory,
  AT.AppointmentType,
  COALESCE(AB.SubAppointmentType, '') AS SubAppointmentType,
  AP.AppointmentStage,
  AP.EmployeeParticulars,
  AP.InvoiceNumber,
  ROUND(AP.TimeTravelled * AP.TimeTravelledRate, 2) AS TravelTime,
  ROUND(AP.DistanceTravelled * AP.DistanceTravelledRate, 2) AS TravelDistance,
  ROUND(AP.TimeTravelled * AP.TimeTravelledRate, 2) + ROUND(AP.DistanceTravelled * AP.DistanceTravelledRate, 2) AS TravelValue,
  AP.CoverUsed AS CoverAmount,
  AP.FreeTimeAmount,
  AP.ServiceValue,
  AT.IsService,
  '' AS Auth
FROM
  tbAppointments AS AP
    LEFT JOIN tbAppointmentTypes     AS AT ON (AT.AttendanceTypeID      = AP.AttendanceTypeID)
    LEFT JOIN taAppointmentSubType   AS AB ON (AB.SubTypeID             = AP.SubAttendanceType)
    LEFT JOIN taClientBranchProducts AS BP ON (BP.ClientBranchProductID = AP.ClientBranchProductID)
    LEFT JOIN taClientProducts       AS CP ON (CP.ClientProductID       = BP.ClientProductID)
    LEFT JOIN taClientBranches       AS CB ON (CB.ClientBranchID        = AP.ClientBranchID)
    LEFT JOIN taClients              AS CS ON (CS.ClientID              = AP.ClientID)
    LEFT JOIN taUsers                AS U1 ON (U1.UserID                = AP.ConsultantID)
    LEFT JOIN taUsers                AS U2 ON (U2.UserID                = AP.BookedByID)
    LEFT JOIN taBranches             AS BR ON (BR.BranchID = AP.ConsultantBranchID)
    LEFT JOIN taBranches             AS B3 ON (B3.BranchID = CB.LabourNetBranchID)
    @pJoinForFilter
WHERE
  (AP.AppointmentID IS NOT NULL)
  @pAppointmentStatus
  @pConsultantID
  @pClientID
  @pCaseID
  @pFilter
  @pProductID
  @pBranchID
  @pFromTo
