SELECT
  X.*,
  fnClientBranchProductRetainer(X.ClientBranchProductID, @aTargetDate) * 1.0 AS Retainer,
  fnServiceValue(X.ClientBranchProductID, @aFromDate, @aToDate) AS ServiceValue,
  0 AS LabourNetBranchError,
  0.0 AS ServiceValuePercentage,
  0.0 AS SuggestedRetainer
FROM (

  SELECT
    CB.ClientID,
    CP.ProductID,
    BP.ClientBranchID,
    BP.ClientProductID,
    BP.ClientBranchProductID,
    CB.LabourNetBranchID,
    BP.ConsultantID,
    CB.BranchName AS ClientBranchName,
    IF(BP.Status = 1, 'ACTIVE', 'CANCELLED') AS Status,
    CB.NoOfEmployees,
    BR.BranchName AS LabourNetBranchName,
    U1.FullName AS Consultant
  FROM
    taClientBranchProducts AS BP
      LEFT JOIN taClientBranches AS CB ON (CB.ClientBranchID = BP.ClientBranchID)
      LEFT JOIN taClientProducts AS CP ON (CP.ClientProductID = BP.ClientProductID)
      LEFT JOIN taUsers AS U1 ON (U1.UserID = BP.ConsultantID)
      LEFT JOIN taBranches AS BR ON (BR.BranchID = CB.LabourNetBranchID)
  WHERE
    (BP.Status = 1) AND
    (BP.ClientProductID = @nClientProductID)
  ORDER BY
    BP.JoinDate

) AS X
ORDER BY X.LabourNetBranchID, X.ConsultantID, X.ClientBranchID